﻿using KernelRecordsMVC.Application.ViewModels;
using KernelRecordsMVC.Domain.Enums;
using KernelRecordsMVC.Infrastructure.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace KernelRecordsMVC.Web.Controllers;

public class SaleController : Controller
{
    private readonly KernelRecordsContext _context;

    public SaleController(KernelRecordsContext context)
    {
        _context = context;
    }

    public IActionResult Index()
    {
        var products = _context.Products
            .Include(p => p.Release)
                .ThenInclude(r => r.ReleaseArtists)
                    .ThenInclude(ra => ra.Artist)
            .Include(p => p.ModificationProducts)
                .ThenInclude(mp => mp.Modification)
            .ToList();


        var result = new List<SaleItemViewModel>();


        foreach (var product in products)
        {
            // Get the latest modification for this product.
            var latestModification = product.ModificationProducts
                .Select(x => x.Modification)
                .OrderByDescending(m => m.DateModified)
                .ThenByDescending(m => m.ModificationId)
                .FirstOrDefault();


            // Product is only considered currently on sale
            // if its latest modification is a discount.
            if (latestModification == null ||
                latestModification.TypeOfModification != ModificationType.DISCOUNT ||
                !latestModification.Discount.HasValue ||
                latestModification.Discount.Value <= 0)
            {
                continue;
            }


            var percentage =
                latestModification.Discount.Value;


            // IMPORTANT:
            // Product.Price already contains the discounted price.
            var salePrice =
                product.Price;


            // Reconstruct the price before the discount
            // so it can be displayed crossed out.
            var originalPrice =
                percentage > 0 &&
                percentage < 100
                    ? Math.Round(
                        salePrice /
                        (1m - percentage / 100m),
                        2,
                        MidpointRounding.AwayFromZero)
                    : salePrice;


            result.Add(new SaleItemViewModel
            {
                ProductId =
                    product.ProductId,

                ReleaseId =
                    product.ReleaseId,

                ReleaseTitle =
                    product.Release.Title,

                CoverPhoto =
                    product.Release.CoverPhoto,

                Format =
                    product.Format.ToString(),

                OriginalPrice =
                    originalPrice,

                SalePrice =
                    salePrice,

                DiscountPercentage =
                    percentage,

                Stock =
                    product.Stock,

                ArtistName =
                    string.Join(
                        ", ",
                        product.Release.ReleaseArtists
                            .OrderBy(x => x.ReleaseOrdinal)
                            .Select(x => x.Artist.ArtistName))
            });
        }


        result = result
            .OrderByDescending(x =>
                x.DiscountPercentage)
            .ThenBy(x =>
                x.ReleaseTitle)
            .ToList();


        return View(result);
    }
}