namespace TaxBaik.Infrastructure.Repositories;

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

public class PortalUserRepository(IDbConnectionFactory connectionFactory) : BaseRepository(connectionFactory), IPortalUserRepository
{
    public async Task<PortalUser?> GetByIdAsync(int id, CancellationToken ct = default)
    {
        using var conn = Conn();
        return await conn.QueryFirstOrDefaultAsync<PortalUser>(
            @"SELECT id, client_id, email, name, phone, provider, provider_id, password_hash, created_at
              FROM portal_users
              WHERE id = @Id",
            new { Id = id });
    }

    public async Task<PortalUser?> GetByEmailAsync(string email, CancellationToken ct = default)
    {
        using var conn = Conn();
        return await conn.QueryFirstOrDefaultAsync<PortalUser>(
            @"SELECT id, client_id, email, name, phone, provider, provider_id, password_hash, created_at
              FROM portal_users
              WHERE email = @Email",
            new { Email = email });
    }

    public async Task<PortalUser?> GetByProviderAsync(string provider, string providerId, CancellationToken ct = default)
    {
        using var conn = Conn();
        return await conn.QueryFirstOrDefaultAsync<PortalUser>(
            @"SELECT id, client_id, email, name, phone, provider, provider_id, password_hash, created_at
              FROM portal_users
              WHERE provider = @Provider AND provider_id = @ProviderId",
            new { Provider = provider, ProviderId = providerId });
    }

    public async Task<int> CreateAsync(PortalUser user, CancellationToken ct = default)
    {
        using var conn = Conn();
        return await conn.QueryFirstAsync<int>(
            @"INSERT INTO portal_users (client_id, email, name, phone, provider, provider_id, password_hash, created_at)
              VALUES (@ClientId, @Email, @Name, @Phone, @Provider, @ProviderId, @PasswordHash, NOW())
              RETURNING id",
            user);
    }

    public async Task UpdateAsync(PortalUser user, CancellationToken ct = default)
    {
        using var conn = Conn();
        await conn.ExecuteAsync(
            @"UPDATE portal_users
              SET client_id = @ClientId,
                  email = @Email,
                  name = @Name,
                  phone = @Phone,
                  provider = @Provider,
                  provider_id = @ProviderId,
                  password_hash = @PasswordHash
              WHERE id = @Id",
            user);
    }
}
