using Indotalent.ConfigBackEnd.Exceptions;
using Indotalent.ConfigBackEnd.Extensions;
using Indotalent.Infrastructure.Database;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Setting.Currency.Cqrs;

public class CreateCurrencyRequest
{
    public string? Code { get; set; }
    public string? Name { get; set; }
    public string? Symbol { get; set; }
    public string? CountryOwner { get; set; }
    public string? Description { get; set; }
}

public class CreateCurrencyResponse
{
    public string? Id { get; set; }
    public string? Code { get; set; }
}

public record CreateCurrencyCommand(CreateCurrencyRequest Data) : IRequest<CreateCurrencyResponse>;
public class CreateCurrencyHandler : IRequestHandler<CreateCurrencyCommand, CreateCurrencyResponse>
{
    private readonly AppDbContext _context;

    public CreateCurrencyHandler(AppDbContext context) => _context = context;

    public async Task<CreateCurrencyResponse> Handle(CreateCurrencyCommand request, CancellationToken cancellationToken)
    {
        var isExists = await _context.Currency
            .AnyAsync(x => x.Code == request.Data.Code, cancellationToken);

        if (isExists)
        {
            throw new AlreadyExistsException("Currency", request.Data.Code ?? string.Empty);
        }

        var entityName = nameof(Currency);

        var autoNo = await _context.GenerateAutoNumberAsync(
            entityName: entityName,
            prefixTemplate: $"{entityName.ToShortNameConsonant(3)}/{{Year}}/",
            ct: cancellationToken
        );

        var entity = new Data.Entities.Currency
        {
            AutoNumber = autoNo,
            Code = request.Data.Code,
            Name = request.Data.Name,
            Symbol = request.Data.Symbol,
            CountryOwner = request.Data.CountryOwner,
            Description = request.Data.Description
        };

        _context.Currency.Add(entity);
        await _context.SaveChangesAsync(cancellationToken);

        return new CreateCurrencyResponse
        {
            Id = entity.Id,
            Code = entity.Code
        };
    }
}