using Dapper;
using TaxBaik.Domain.Entities;
using TaxBaik.Domain.Interfaces;

namespace TaxBaik.Infrastructure.Repositories;

public class AdminUserRepository : BaseRepository, IAdminUserRepository
{
    public AdminUserRepository(IDbConnectionFactory connectionFactory) : base(connectionFactory) { }

    public async Task<AdminUser?> GetByUsernameAsync(string username)
    {
        using var conn = _connectionFactory.CreateConnection();
        return await conn.QueryFirstOrDefaultAsync<AdminUser>(
            """
            SELECT
                id,
                username,
                password_hash AS PasswordHash,
                last_login_at AS LastLoginAt,
                created_at AS CreatedAt
            FROM admin_users
            WHERE username = @username
            """,
            new { username });
    }

    public async Task<AdminUser?> GetByIdAsync(int id)
    {
        using var conn = _connectionFactory.CreateConnection();
        return await conn.QueryFirstOrDefaultAsync<AdminUser>(
            """
            SELECT
                id,
                username,
                password_hash AS PasswordHash,
                last_login_at AS LastLoginAt,
                created_at AS CreatedAt
            FROM admin_users
            WHERE id = @id
            """,
            new { id });
    }

    public async Task CreateAsync(AdminUser user)
    {
        using var conn = _connectionFactory.CreateConnection();
        await conn.ExecuteAsync(
            "INSERT INTO admin_users (username, password_hash, created_at) VALUES (@username, @passwordHash, NOW())",
            new { username = user.Username, passwordHash = user.PasswordHash });
    }

    public async Task UpdatePasswordHashAsync(int id, string passwordHash)
    {
        using var conn = _connectionFactory.CreateConnection();
        await conn.ExecuteAsync(
            "UPDATE admin_users SET password_hash = @passwordHash WHERE id = @id",
            new { id, passwordHash });
    }

    public async Task UpdateLastLoginAtAsync(int id)
    {
        using var conn = _connectionFactory.CreateConnection();
        await conn.ExecuteAsync(
            "UPDATE admin_users SET last_login_at = NOW() WHERE id = @id",
            new { id });
    }
}
