namespace TaxBaik.Infrastructure.Repositories;

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

public class FaqRepository(IDbConnectionFactory connectionFactory) : BaseRepository(connectionFactory), IFaqRepository
{
    private const string SelectColumns =
        "id, question, answer, category, sort_order, is_active, created_at, updated_at";

    public async Task<IEnumerable<Faq>> GetActiveAsync(CancellationToken ct = default)
    {
        using var conn = Conn();
        return await conn.QueryAsync<Faq>(
            $"SELECT {SelectColumns} FROM faqs WHERE is_active = TRUE ORDER BY sort_order, id");
    }

    public async Task<IEnumerable<Faq>> GetAllAsync(CancellationToken ct = default)
    {
        using var conn = Conn();
        return await conn.QueryAsync<Faq>(
            $"SELECT {SelectColumns} FROM faqs ORDER BY sort_order, id");
    }

    public async Task<Faq?> GetByIdAsync(int id, CancellationToken ct = default)
    {
        using var conn = Conn();
        return await conn.QueryFirstOrDefaultAsync<Faq>(
            $"SELECT {SelectColumns} FROM faqs WHERE id = @Id",
            new { Id = id });
    }

    public async Task<int> CreateAsync(Faq faq, CancellationToken ct = default)
    {
        using var conn = Conn();
        return await conn.QueryFirstAsync<int>(
            @"INSERT INTO faqs (question, answer, category, sort_order, is_active, created_at, updated_at)
              VALUES (@Question, @Answer, @Category, @SortOrder, @IsActive, NOW(), NOW())
              RETURNING id",
            faq);
    }

    public async Task UpdateAsync(Faq faq, CancellationToken ct = default)
    {
        using var conn = Conn();
        await conn.ExecuteAsync(
            @"UPDATE faqs
              SET question = @Question, answer = @Answer, category = @Category,
                  sort_order = @SortOrder, is_active = @IsActive, updated_at = NOW()
              WHERE id = @Id",
            faq);
    }

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