using foodmarket.Application.Catalog;
using foodmarket.Application.Common;
using foodmarket.Domain.Catalog;
using foodmarket.Infrastructure.Persistence;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace foodmarket.Api.Controllers.Catalog;

[ApiController]
[Authorize]
[Route("api/catalog/currencies")]
public class CurrenciesController : ControllerBase
{
    private readonly AppDbContext _db;

    public CurrenciesController(AppDbContext db) => _db = db;

    [HttpGet]
    public async Task<ActionResult<PagedResult<CurrencyDto>>> List([FromQuery] PagedRequest req, CancellationToken ct)
    {
        var q = _db.Currencies.AsNoTracking().AsQueryable();
        if (!string.IsNullOrWhiteSpace(req.Search))
        {
            var s = req.Search.Trim().ToLower();
            q = q.Where(c => c.Name.ToLower().Contains(s) || c.Code.ToLower().Contains(s));
        }
        var total = await q.CountAsync(ct);
        q = (req.Sort, req.Desc) switch
        {
            ("name", false) => q.OrderBy(c => c.Name),
            ("name", true) => q.OrderByDescending(c => c.Name),
            ("symbol", false) => q.OrderBy(c => c.Symbol),
            ("symbol", true) => q.OrderByDescending(c => c.Symbol),
            ("code", true) => q.OrderByDescending(c => c.Code),
            _ => q.OrderBy(c => c.Code),
        };
        var items = await q
            .Skip(req.Skip).Take(req.Take)
            .Select(c => new CurrencyDto(c.Id, c.Code, c.Name, c.Symbol))
            .ToListAsync(ct);
        return new PagedResult<CurrencyDto> { Items = items, Total = total, Page = req.Page, PageSize = req.Take };
    }

    [HttpGet("{id:guid}")]
    public async Task<ActionResult<CurrencyDto>> Get(Guid id, CancellationToken ct)
    {
        var c = await _db.Currencies.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id, ct);
        return c is null ? NotFound() : new CurrencyDto(c.Id, c.Code, c.Name, c.Symbol);
    }

    [HttpPost, Authorize(Roles = "SuperAdmin")]
    public async Task<ActionResult<CurrencyDto>> Create([FromBody] CurrencyInput input, CancellationToken ct)
    {
        var e = new Currency
        {
            Code = input.Code.Trim().ToUpper(),
            Name = input.Name,
            Symbol = input.Symbol,
        };
        _db.Currencies.Add(e);
        await _db.SaveChangesAsync(ct);
        return CreatedAtAction(nameof(Get), new { id = e.Id },
            new CurrencyDto(e.Id, e.Code, e.Name, e.Symbol));
    }

    [HttpPut("{id:guid}"), Authorize(Roles = "SuperAdmin")]
    public async Task<IActionResult> Update(Guid id, [FromBody] CurrencyInput input, CancellationToken ct)
    {
        var e = await _db.Currencies.FirstOrDefaultAsync(x => x.Id == id, ct);
        if (e is null) return NotFound();
        e.Code = input.Code.Trim().ToUpper();
        e.Name = input.Name;
        e.Symbol = input.Symbol;
        await _db.SaveChangesAsync(ct);
        return NoContent();
    }
}
