using Microsoft.EntityFrameworkCore;
using ROLAC.API.Data;
using ROLAC.API.DTOs.Giving;
using ROLAC.API.Entities;

namespace ROLAC.API.Services;

public class GivingCategoryService : IGivingCategoryService
{
    private readonly AppDbContext _db;
    public GivingCategoryService(AppDbContext db) => _db = db;

    public async Task<List<GivingCategoryDto>> GetAllAsync(bool includeInactive)
    {
        var query = _db.GivingCategories.AsNoTracking().AsQueryable();
        if (!includeInactive) query = query.Where(c => c.IsActive);

        return await query
            .OrderBy(c => c.SortOrder).ThenBy(c => c.Name_en)
            .Select(c => new GivingCategoryDto
            {
                Id = c.Id, Name_en = c.Name_en, Name_zh = c.Name_zh,
                Description_en = c.Description_en, Description_zh = c.Description_zh,
                IsActive = c.IsActive, SortOrder = c.SortOrder,
            })
            .ToListAsync();
    }

    public async Task<int> CreateAsync(CreateGivingCategoryRequest r)
    {
        var entity = new GivingCategory
        {
            Name_en = r.Name_en, Name_zh = r.Name_zh,
            Description_en = r.Description_en, Description_zh = r.Description_zh,
            SortOrder = r.SortOrder, IsActive = true,
        };
        _db.GivingCategories.Add(entity);
        await _db.SaveChangesAsync();
        return entity.Id;
    }

    public async Task UpdateAsync(int id, UpdateGivingCategoryRequest r)
    {
        var c = await _db.GivingCategories.FindAsync(id)
            ?? throw new KeyNotFoundException($"GivingCategory {id} not found.");
        c.Name_en = r.Name_en; c.Name_zh = r.Name_zh;
        c.Description_en = r.Description_en; c.Description_zh = r.Description_zh;
        c.IsActive = r.IsActive; c.SortOrder = r.SortOrder;
        await _db.SaveChangesAsync();
    }

    public async Task DeactivateAsync(int id)
    {
        var c = await _db.GivingCategories.FindAsync(id)
            ?? throw new KeyNotFoundException($"GivingCategory {id} not found.");
        c.IsActive = false;
        await _db.SaveChangesAsync();
    }
}
