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>Designation (job title) master service (FR-HR-MD-01, docs/13-BACKEND-HRM-API.md §2).</summary>
public sealed class DesignationService : IDesignationService
{
    private readonly IRepository<Designation> _designations;
    private readonly IUnitOfWork _uow;

    public DesignationService(IRepository<Designation> designations, IUnitOfWork uow)
    {
        _designations = designations;
        _uow = uow;
    }

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

        var total = await q.CountAsync(ct);
        var rows = await q.OrderBy(d => d.Name)
            .Skip(query.Skip).Take(query.PageSize)
            .Select(d => new DesignationDto(d.DesignationId, d.Code, d.Name, d.Status, d.CreatedAt, d.UpdatedAt))
            .ToListAsync(ct);

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

    public async Task<ETagged<DesignationDto>?> GetAsync(int designationId, CancellationToken ct = default)
    {
        var designation = await _designations.Query().AsNoTracking().FirstOrDefaultAsync(d => d.DesignationId == designationId, ct);
        return designation is null ? null : new ETagged<DesignationDto>(Map(designation), designation.RowVersion);
    }

    public async Task<ETagged<DesignationDto>> CreateAsync(CreateDesignationRequest request, CancellationToken ct = default)
    {
        var code = request.Code.Trim();
        if (await _designations.Query().AnyAsync(d => d.Code.ToLower() == code.ToLower(), ct))
            throw new ConflictException($"A designation with code '{code}' already exists.");

        var designation = new Designation
        {
            Code = code,
            Name = request.Name.Trim(),
            Status = EntityStatus.Active,
            CreatedAt = DateTime.UtcNow
        };

        await _designations.AddAsync(designation, ct);
        await _uow.SaveChangesAsync(ct);

        return new ETagged<DesignationDto>(Map(designation), designation.RowVersion);
    }

    public async Task<ETagged<DesignationDto>> UpdateAsync(int designationId, UpdateDesignationRequest request, uint expectedRowVersion, CancellationToken ct = default)
    {
        var designation = await _designations.GetByIdAsync(designationId, ct)
            ?? throw new NotFoundException($"Designation {designationId} was not found.");

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

        designation.Name = request.Name.Trim();
        designation.UpdatedAt = DateTime.UtcNow;

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

        return new ETagged<DesignationDto>(Map(designation), designation.RowVersion);
    }

    public async Task SetStatusAsync(int designationId, EntityStatus status, CancellationToken ct = default)
    {
        var designation = await _designations.GetByIdAsync(designationId, ct)
            ?? throw new NotFoundException($"Designation {designationId} was not found.");

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

    private static DesignationDto Map(Designation d) => new(d.DesignationId, d.Code, d.Name, d.Status, d.CreatedAt, d.UpdatedAt);
}
