using ERPCore.Common.Http;
using ERPCore.Domain.Entities;
using ERPCore.Domain.Enums;
using ERPCore.Dtos.Common;
using ERPCore.Dtos.Hrm;
using ERPCore.Infra.UoW;
using ERPCore.Repositories.Interfaces;
using ERPCore.Services.Interfaces;
using ERPCore.System.Errors;
using Microsoft.EntityFrameworkCore;

namespace ERPCore.Services.Hrm;

/// <summary>Staff document-type catalog service (FR-HR-DOC-01, docs/13-BACKEND-HRM-API.md §2).</summary>
public sealed class HrDocumentTypeService : IHrDocumentTypeService
{
    private readonly IRepository<HrDocumentType> _types;
    private readonly IUnitOfWork _uow;

    public HrDocumentTypeService(IRepository<HrDocumentType> types, IUnitOfWork uow)
    {
        _types = types;
        _uow = uow;
    }

    public async Task<PagedResponse<HrDocumentTypeDto>> ListAsync(PageQuery query, EntityStatus? status, CancellationToken ct = default)
    {
        var q = _types.Query().AsNoTracking();
        if (!string.IsNullOrWhiteSpace(query.Q))
        {
            var term = query.Q.Trim();
            q = q.Where(t => EF.Functions.ILike(t.Name, $"%{term}%") || EF.Functions.ILike(t.Code, $"%{term}%"));
        }
        if (status is not null) q = q.Where(t => t.Status == status);

        var total = await q.CountAsync(ct);
        var rows = await q.OrderBy(t => t.Name)
            .Skip(query.Skip).Take(query.PageSize)
            .Select(t => Map(t))
            .ToListAsync(ct);

        return PagedResponse<HrDocumentTypeDto>.Create(rows, query.Page, query.PageSize, total);
    }

    public async Task<ETagged<HrDocumentTypeDto>?> GetAsync(int hrDocumentTypeId, CancellationToken ct = default)
    {
        var type = await _types.Query().AsNoTracking().FirstOrDefaultAsync(t => t.HrDocumentTypeId == hrDocumentTypeId, ct);
        return type is null ? null : new ETagged<HrDocumentTypeDto>(Map(type), type.RowVersion);
    }

    public async Task<ETagged<HrDocumentTypeDto>> CreateAsync(CreateHrDocumentTypeRequest request, CancellationToken ct = default)
    {
        var code = request.Code.Trim();
        if (await _types.Query().AnyAsync(t => t.Code.ToLower() == code.ToLower(), ct))
            throw new ConflictException($"A document type with code '{code}' already exists.");

        var type = new HrDocumentType
        {
            Code = code,
            Name = request.Name.Trim(),
            Category = request.Category,
            RequiredAtOnboarding = request.RequiredAtOnboarding,
            ExpiryTracked = request.ExpiryTracked,
            Status = EntityStatus.Active,
            CreatedAt = DateTime.UtcNow
        };

        await _types.AddAsync(type, ct);
        await _uow.SaveChangesAsync(ct);

        return new ETagged<HrDocumentTypeDto>(Map(type), type.RowVersion);
    }

    public async Task<ETagged<HrDocumentTypeDto>> UpdateAsync(
        int hrDocumentTypeId, UpdateHrDocumentTypeRequest request, uint expectedRowVersion, CancellationToken ct = default)
    {
        var type = await _types.GetByIdAsync(hrDocumentTypeId, ct)
            ?? throw new NotFoundException($"Document type {hrDocumentTypeId} was not found.");

        if (type.RowVersion != expectedRowVersion)
            throw new DomainException(ErrorCodes.ConcurrencyConflict, "The document type was modified by another request.", 412);

        type.Name = request.Name.Trim();
        type.Category = request.Category;
        type.RequiredAtOnboarding = request.RequiredAtOnboarding;
        type.ExpiryTracked = request.ExpiryTracked;
        type.UpdatedAt = DateTime.UtcNow;

        try
        {
            await _uow.SaveChangesAsync(ct);
        }
        catch (DbUpdateConcurrencyException)
        {
            throw new DomainException(ErrorCodes.ConcurrencyConflict, "The document type was modified by another request.", 412);
        }

        return new ETagged<HrDocumentTypeDto>(Map(type), type.RowVersion);
    }

    public async Task SetStatusAsync(int hrDocumentTypeId, EntityStatus status, CancellationToken ct = default)
    {
        var type = await _types.GetByIdAsync(hrDocumentTypeId, ct)
            ?? throw new NotFoundException($"Document type {hrDocumentTypeId} was not found.");

        type.Status = status;
        type.UpdatedAt = DateTime.UtcNow;
        await _uow.SaveChangesAsync(ct);
    }

    private static HrDocumentTypeDto Map(HrDocumentType t) => new(
        t.HrDocumentTypeId, t.Code, t.Name, t.Category, t.RequiredAtOnboarding, t.ExpiryTracked, t.Status, t.CreatedAt, t.UpdatedAt);
}
