namespace TaxBaik.Infrastructure.Repositories;

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

public class ConsultationRepository(IDbConnectionFactory connectionFactory) : BaseRepository(connectionFactory), IConsultationRepository
{
    public async Task<IEnumerable<Consultation>> GetByClientIdAsync(int clientId, CancellationToken ct = default)
    {
        using var conn = Conn();
        return await conn.QueryAsync<Consultation>(
            @"SELECT id, client_id, consultation_date, service_type, summary, result, fee, created_at
              FROM consultations
              WHERE client_id = @ClientId
              ORDER BY consultation_date DESC, id DESC",
            new { ClientId = clientId });
    }

    public async Task<int> CreateAsync(Consultation consultation, CancellationToken ct = default)
    {
        using var conn = Conn();
        return await conn.QueryFirstAsync<int>(
            @"INSERT INTO consultations (client_id, consultation_date, service_type, summary, result, fee, created_at)
              VALUES (@ClientId, @ConsultationDate, @ServiceType, @Summary, @Result, @Fee, NOW())
              RETURNING id",
            consultation);
    }

    public async Task DeleteAsync(int id, CancellationToken ct = default)
    {
        using var conn = Conn();
        await conn.ExecuteAsync("DELETE FROM consultations WHERE id = @Id", new { Id = id });
    }
}
