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>EmploymentType master service (FR-HR-MD-01, docs/13-BACKEND-HRM-API.md §2).</summary>
public sealed class EmploymentTypeService : IEmploymentTypeService
{
    private readonly IRepository<EmploymentType> _employmentTypes;
    private readonly IUnitOfWork _uow;

    public EmploymentTypeService(IRepository<EmploymentType> employmentTypes, IUnitOfWork uow)
    {
        _employmentTypes = employmentTypes;
        _uow = uow;
    }

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

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

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

    public async Task<ETagged<EmploymentTypeDto>?> GetAsync(int employmentTypeId, CancellationToken ct = default)
    {
        var et = await _employmentTypes.Query().AsNoTracking().FirstOrDefaultAsync(e => e.EmploymentTypeId == employmentTypeId, ct);
        return et is null ? null : new ETagged<EmploymentTypeDto>(Map(et), et.RowVersion);
    }

    public async Task<ETagged<EmploymentTypeDto>> CreateAsync(CreateEmploymentTypeRequest request, CancellationToken ct = default)
    {
        var code = request.Code.Trim();
        if (await _employmentTypes.Query().AnyAsync(e => e.Code.ToLower() == code.ToLower(), ct))
            throw new ConflictException($"An employment type with code '{code}' already exists.");

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

        await _employmentTypes.AddAsync(et, ct);
        await _uow.SaveChangesAsync(ct);

        return new ETagged<EmploymentTypeDto>(Map(et), et.RowVersion);
    }

    public async Task<ETagged<EmploymentTypeDto>> UpdateAsync(int employmentTypeId, UpdateEmploymentTypeRequest request, uint expectedRowVersion, CancellationToken ct = default)
    {
        var et = await _employmentTypes.GetByIdAsync(employmentTypeId, ct)
            ?? throw new NotFoundException($"Employment type {employmentTypeId} was not found.");

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

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

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

        return new ETagged<EmploymentTypeDto>(Map(et), et.RowVersion);
    }

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

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

    private static EmploymentTypeDto Map(EmploymentType e) => new(e.EmploymentTypeId, e.Code, e.Name, e.Status, e.CreatedAt, e.UpdatedAt);
}
