namespace TaxBaik.Infrastructure.Repositories;

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

public class CategoryRepository(IDbConnectionFactory connectionFactory) : BaseRepository(connectionFactory), ICategoryRepository
{
    public async Task<IEnumerable<Category>> GetAllAsync(CancellationToken cancellationToken = default)
    {
        using var conn = Conn();
        return await conn.QueryAsync<Category>(
            "SELECT id, name, slug, sort_order FROM categories ORDER BY sort_order");
    }

    public async Task<Category?> GetBySlugAsync(string slug, CancellationToken cancellationToken = default)
    {
        using var conn = Conn();
        return await conn.QueryFirstOrDefaultAsync<Category>(
            "SELECT id, name, slug, sort_order FROM categories WHERE slug = @Slug",
            new { Slug = slug });
    }

    public async Task<Category?> GetByIdAsync(int id, CancellationToken cancellationToken = default)
    {
        using var conn = Conn();
        return await conn.QueryFirstOrDefaultAsync<Category>(
            "SELECT id, name, slug, sort_order FROM categories WHERE id = @Id",
            new { Id = id });
    }

    public async Task<int> CreateAsync(Category category, CancellationToken cancellationToken = default)
    {
        using var conn = Conn();
        return await conn.QueryFirstAsync<int>(
            @"INSERT INTO categories (name, slug, sort_order)
              VALUES (@Name, @Slug, @SortOrder)
              RETURNING id",
            category);
    }

    public async Task UpdateAsync(Category category, CancellationToken cancellationToken = default)
    {
        using var conn = Conn();
        await conn.ExecuteAsync(
            "UPDATE categories SET name = @Name, slug = @Slug, sort_order = @SortOrder WHERE id = @Id",
            category);
    }

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