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/stores")]
public class StoresController : ControllerBase
{
    private readonly AppDbContext _db;

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

    [HttpGet]
    public async Task<ActionResult<PagedResult<StoreDto>>> List([FromQuery] PagedRequest req, CancellationToken ct)
    {
        var q = _db.Stores.AsNoTracking().AsQueryable();
        if (!string.IsNullOrWhiteSpace(req.Search))
        {
            var s = req.Search.Trim().ToLower();
            q = q.Where(x => x.Name.ToLower().Contains(s) || (x.Code != null && x.Code.ToLower().Contains(s)));
        }
        var total = await q.CountAsync(ct);
        q = (req.Sort, req.Desc) switch
        {
            ("name", false) => q.OrderBy(x => x.Name),
            ("name", true) => q.OrderByDescending(x => x.Name),
            ("code", false) => q.OrderBy(x => x.Code).ThenBy(x => x.Name),
            ("code", true) => q.OrderByDescending(x => x.Code).ThenBy(x => x.Name),
            ("address", false) => q.OrderBy(x => x.Address).ThenBy(x => x.Name),
            ("address", true) => q.OrderByDescending(x => x.Address).ThenBy(x => x.Name),
            ("isMain", false) => q.OrderBy(x => x.IsMain).ThenBy(x => x.Name),
            ("isMain", true) => q.OrderByDescending(x => x.IsMain).ThenBy(x => x.Name),
            ("isActive", false) => q.OrderBy(x => x.IsActive).ThenBy(x => x.Name),
            ("isActive", true) => q.OrderByDescending(x => x.IsActive).ThenBy(x => x.Name),
            _ => q.OrderByDescending(x => x.IsMain).ThenBy(x => x.Name),
        };
        var items = await q
            .Skip(req.Skip).Take(req.Take)
            .Select(x => new StoreDto(x.Id, x.Name, x.Code, x.Address, x.Phone, x.ManagerName, x.IsMain, x.IsActive))
            .ToListAsync(ct);
        return new PagedResult<StoreDto> { Items = items, Total = total, Page = req.Page, PageSize = req.Take };
    }

    [HttpGet("{id:guid}")]
    public async Task<ActionResult<StoreDto>> Get(Guid id, CancellationToken ct)
    {
        var x = await _db.Stores.AsNoTracking().FirstOrDefaultAsync(s => s.Id == id, ct);
        return x is null ? NotFound() : new StoreDto(x.Id, x.Name, x.Code, x.Address, x.Phone, x.ManagerName, x.IsMain, x.IsActive);
    }

    [HttpPost, Authorize(Roles = "Admin")]
    public async Task<ActionResult<StoreDto>> Create([FromBody] StoreInput input, CancellationToken ct)
    {
        if (input.IsMain)
        {
            await _db.Stores.Where(s => s.IsMain).ExecuteUpdateAsync(s => s.SetProperty(x => x.IsMain, false), ct);
        }
        var e = new Store
        {
            Name = input.Name, Code = input.Code,Address = input.Address,
            Phone = input.Phone, ManagerName = input.ManagerName, IsMain = input.IsMain, IsActive = input.IsActive,
        };
        _db.Stores.Add(e);
        await _db.SaveChangesAsync(ct);
        return CreatedAtAction(nameof(Get), new { id = e.Id },
            new StoreDto(e.Id, e.Name, e.Code, e.Address, e.Phone, e.ManagerName, e.IsMain, e.IsActive));
    }

    [HttpPut("{id:guid}"), Authorize(Roles = "Admin")]
    public async Task<IActionResult> Update(Guid id, [FromBody] StoreInput input, CancellationToken ct)
    {
        var e = await _db.Stores.FirstOrDefaultAsync(x => x.Id == id, ct);
        if (e is null) return NotFound();
        if (input.IsMain && !e.IsMain)
        {
            await _db.Stores.Where(s => s.IsMain && s.Id != id).ExecuteUpdateAsync(s => s.SetProperty(x => x.IsMain, false), ct);
        }
        e.Name = input.Name;
        e.Code = input.Code;
        
        e.Address = input.Address;
        e.Phone = input.Phone;
        e.ManagerName = input.ManagerName;
        e.IsMain = input.IsMain;
        e.IsActive = input.IsActive;
        await _db.SaveChangesAsync(ct);
        return NoContent();
    }

    [HttpDelete("{id:guid}"), Authorize(Roles = "Admin")]
    public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
    {
        var e = await _db.Stores.FirstOrDefaultAsync(x => x.Id == id, ct);
        if (e is null) return NotFound();
        _db.Stores.Remove(e);
        await _db.SaveChangesAsync(ct);
        return NoContent();
    }
}
