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

    public BranchService(IRepository<Branch> branches, IUnitOfWork uow)
    {
        _branches = branches;
        _uow = uow;
    }

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

        var total = await q.CountAsync(ct);
        var rows = await q.OrderBy(b => b.Name)
            .Skip(query.Skip).Take(query.PageSize)
            .Select(b => new BranchDto(b.BranchId, b.Code, b.Name, b.Address, b.Status, b.CreatedAt, b.UpdatedAt))
            .ToListAsync(ct);

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

    public async Task<ETagged<BranchDto>?> GetAsync(int branchId, CancellationToken ct = default)
    {
        var branch = await _branches.Query().AsNoTracking().FirstOrDefaultAsync(b => b.BranchId == branchId, ct);
        return branch is null ? null : new ETagged<BranchDto>(Map(branch), branch.RowVersion);
    }

    public async Task<ETagged<BranchDto>> CreateAsync(CreateBranchRequest request, CancellationToken ct = default)
    {
        var code = request.Code.Trim();
        if (await _branches.Query().AnyAsync(b => b.Code.ToLower() == code.ToLower(), ct))
            throw new ConflictException($"A branch with code '{code}' already exists.");

        var branch = new Branch
        {
            Code = code,
            Name = request.Name.Trim(),
            Address = request.Address?.Trim(),
            Status = EntityStatus.Active,
            CreatedAt = DateTime.UtcNow
        };

        await _branches.AddAsync(branch, ct);
        await _uow.SaveChangesAsync(ct);

        return new ETagged<BranchDto>(Map(branch), branch.RowVersion);
    }

    public async Task<ETagged<BranchDto>> UpdateAsync(int branchId, UpdateBranchRequest request, uint expectedRowVersion, CancellationToken ct = default)
    {
        var branch = await _branches.GetByIdAsync(branchId, ct)
            ?? throw new NotFoundException($"Branch {branchId} was not found.");

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

        branch.Name = request.Name.Trim();
        branch.Address = request.Address?.Trim();
        branch.UpdatedAt = DateTime.UtcNow;

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

        return new ETagged<BranchDto>(Map(branch), branch.RowVersion);
    }

    public async Task SetStatusAsync(int branchId, EntityStatus status, CancellationToken ct = default)
    {
        var branch = await _branches.GetByIdAsync(branchId, ct)
            ?? throw new NotFoundException($"Branch {branchId} was not found.");

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

    private static BranchDto Map(Branch b) => new(b.BranchId, b.Code, b.Name, b.Address, b.Status, b.CreatedAt, b.UpdatedAt);
}
