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

namespace ROLAC.API.Services;

public class MinistryService : IMinistryService
{
    private readonly AppDbContext _db;
    public MinistryService(AppDbContext db) => _db = db;

    public async Task<List<MinistryDto>> GetAllAsync(bool includeInactive)
    {
        var query = _db.Ministries.AsNoTracking().AsQueryable();
        if (!includeInactive) query = query.Where(m => m.IsActive);
        return await query
            .OrderBy(m => m.SortOrder).ThenBy(m => m.Name_en)
            .Select(m => new MinistryDto
            {
                Id = m.Id, Name_en = m.Name_en, Name_zh = m.Name_zh,
                Description_en = m.Description_en, Description_zh = m.Description_zh,
                SortOrder = m.SortOrder, IsActive = m.IsActive,
                DefaultFunctionalClass = m.DefaultFunctionalClass,
            })
            .ToListAsync();
    }

    public async Task<int> CreateAsync(CreateMinistryRequest r)
    {
        var entity = new Ministry
        {
            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,
            DefaultFunctionalClass = ROLAC.API.Entities.FunctionalClasses.Normalize(r.DefaultFunctionalClass),
        };
        _db.Ministries.Add(entity);
        await _db.SaveChangesAsync();
        return entity.Id;
    }

    public async Task UpdateAsync(int id, UpdateMinistryRequest r)
    {
        var m = await _db.Ministries.FindAsync(id)
            ?? throw new KeyNotFoundException($"Ministry {id} not found.");
        m.Name_en = r.Name_en; m.Name_zh = r.Name_zh;
        m.Description_en = r.Description_en; m.Description_zh = r.Description_zh;
        m.IsActive = r.IsActive; m.SortOrder = r.SortOrder;
        m.DefaultFunctionalClass = ROLAC.API.Entities.FunctionalClasses.Normalize(r.DefaultFunctionalClass);
        await _db.SaveChangesAsync();
    }

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