using FluentValidation;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SolutionErp.Application.Common.Exceptions;
using SolutionErp.Application.Common.Interfaces;
using SolutionErp.Domain.Master;

namespace SolutionErp.Application.Master.Suppliers.Commands.UpdateSupplier;

public record UpdateSupplierCommand(
    Guid Id,
    string Code,
    string Name,
    SupplierType Type,
    string? TaxCode,
    string? Phone,
    string? Email,
    string? Address,
    string? ContactPerson,
    string? Note) : IRequest;

public class UpdateSupplierCommandValidator : AbstractValidator<UpdateSupplierCommand>
{
    public UpdateSupplierCommandValidator()
    {
        RuleFor(x => x.Id).NotEmpty();
        RuleFor(x => x.Code).NotEmpty().MaximumLength(50);
        RuleFor(x => x.Name).NotEmpty().MaximumLength(200);
        RuleFor(x => x.Type).IsInEnum();
        RuleFor(x => x.Email).EmailAddress().When(x => !string.IsNullOrWhiteSpace(x.Email));
    }
}

public class UpdateSupplierCommandHandler : IRequestHandler<UpdateSupplierCommand>
{
    private readonly IApplicationDbContext _db;

    public UpdateSupplierCommandHandler(IApplicationDbContext db) => _db = db;

    public async Task Handle(UpdateSupplierCommand request, CancellationToken ct)
    {
        var entity = await _db.Suppliers.FirstOrDefaultAsync(x => x.Id == request.Id, ct)
            ?? throw new NotFoundException("Supplier", request.Id);

        if (entity.Code != request.Code &&
            await _db.Suppliers.AnyAsync(x => x.Code == request.Code && x.Id != request.Id, ct))
            throw new ConflictException($"Mã NCC '{request.Code}' đã tồn tại.");

        entity.Code = request.Code;
        entity.Name = request.Name;
        entity.Type = request.Type;
        entity.TaxCode = request.TaxCode;
        entity.Phone = request.Phone;
        entity.Email = request.Email;
        entity.Address = request.Address;
        entity.ContactPerson = request.ContactPerson;
        entity.Note = request.Note;

        await _db.SaveChangesAsync(ct);
    }
}
