using AsadiTools.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace AsadiTools.Pages.Admin.Products;

[Authorize(AuthenticationSchemes = "AdminCookie")]
public class EditModel(AppDbContext db) : PageModel
{
    [BindProperty] public ProductInput Input { get; set; } = new();
    public int ProductId { get; private set; }

    public async Task<IActionResult> OnGetAsync(int id)
    {
        var p = await db.Products.FindAsync(id);
        if (p is null) return NotFound();
        ProductId = id;
        Input = new ProductInput
        {
            NameFa        = p.NameFa,
            NameEn        = p.NameEn,
            Description   = p.Description,
            Price         = p.Price,
            DiscountPrice = p.DiscountPrice,
            Category      = p.Category,
            Brand         = p.Brand,
            Sku           = p.Sku,
            Stock         = p.Stock,
            IsActive      = p.IsActive,
            ImageUrl      = p.ImageUrl,
        };
        return Page();
    }

    public async Task<IActionResult> OnPostAsync(int id)
    {
        if (!ModelState.IsValid) { ProductId = id; return Page(); }
        var p = await db.Products.FindAsync(id);
        if (p is null) return NotFound();

        p.NameFa        = Input.NameFa;
        p.NameEn        = Input.NameEn;
        p.Description   = Input.Description;
        p.Price         = Input.Price;
        p.DiscountPrice = Input.DiscountPrice;
        p.Category      = Input.Category;
        p.Brand         = string.IsNullOrEmpty(Input.Brand) ? null : Input.Brand;
        p.Sku           = Input.Sku;
        p.Stock         = Input.Stock;
        p.IsActive      = Input.IsActive;
        p.ImageUrl      = string.IsNullOrWhiteSpace(Input.ImageUrl) ? null : Input.ImageUrl;

        await db.SaveChangesAsync();
        return RedirectToPage("/Admin/Products/Index");
    }
}
