using AsadiTools.Data;
using AsadiTools.Models;
using AsadiTools.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel.DataAnnotations;

namespace AsadiTools.Pages.Checkout;

public class CheckoutIndexModel(AppDbContext db, CartService cart) : PageModel
{
    [BindProperty]
    public InputModel Input { get; set; } = new();

    public List<CartItem> CartItems { get; private set; } = [];
    public string? OrderNumber { get; private set; }
    public string? ErrorMessage { get; private set; }

    public class InputModel
    {
        [Required(ErrorMessage = "نام الزامی است")]
        public string CustomerName { get; set; } = string.Empty;

        [Required(ErrorMessage = "شماره موبایل الزامی است")]
        public string CustomerPhone { get; set; } = string.Empty;

        public string? CustomerAddress { get; set; }
        public string? Notes { get; set; }
    }

    public IActionResult OnGet()
    {
        CartItems = cart.GetItems();
        if (!CartItems.Any()) return RedirectToPage("/Shop/Index");
        return Page();
    }

    public async Task<IActionResult> OnPostAsync()
    {
        CartItems = cart.GetItems();
        if (!CartItems.Any()) return RedirectToPage("/Shop/Index");

        if (!ModelState.IsValid) return Page();

        var orderNumber = $"ORD-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}";
        var order = new Order
        {
            OrderNumber   = orderNumber,
            CustomerName  = Input.CustomerName,
            CustomerPhone = Input.CustomerPhone,
            CustomerAddress = Input.CustomerAddress,
            Notes         = Input.Notes,
            Items         = CartItems.Select(i => new OrderItem
            {
                ProductId     = i.ProductId,
                ProductNameFa = i.NameFa,
                Price         = i.Price,
                Quantity      = i.Qty,
            }).ToList(),
        };
        order.Subtotal = order.Items.Sum(i => i.Subtotal);
        order.Total    = order.Subtotal;

        db.Orders.Add(order);
        await db.SaveChangesAsync();
        cart.Clear();

        OrderNumber = orderNumber;
        return Page();
    }
}
