using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using StockFin.Models;

namespace StockFin.Controllers;

public class TimeValuesController : Controller
{
    private readonly FinancesContext _context = new FinancesContext();

    //public TimeValuesController(FinancesContext context)
    //{
    //    _context = context;
    //}

    // GET: TimeValues
    public async Task<IActionResult> Index()
    {
        var timeValues = await _context.TimeValues
            .Include(t => t.Stocks)
            .OrderByDescending(t => t.Date)
            .ToListAsync();

        return View(timeValues);
    }

    // GET: TimeValues/Create
    public IActionResult Create()
    {
        PopulateDropdowns();
        return View(new TimeValue { Date = DateTime.Today });
    }

    // POST: TimeValues/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(TimeValue timeValue)
    {
        if (ModelState.IsValid)
        {
            _context.Add(timeValue);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        PopulateDropdowns(timeValue.StocksId);
        return View(timeValue);
        }

        // GET: TimeValues/Edit/5
    public async Task<IActionResult> Edit(long? id)
    {
        if (id is null) return NotFound();

        var timeValue = await _context.TimeValues.FindAsync(id);
        if (timeValue is null) return NotFound();

        PopulateDropdowns(timeValue.StocksId);
        return View(timeValue);
    }

    // POST: TimeValues/Edit/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(long id, TimeValue timeValue)
    {
        if (id != timeValue.Id) return NotFound();

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(timeValue);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TimeValueExists(timeValue.Id)) return NotFound();
                throw;
            }
            return RedirectToAction(nameof(Index));
        }

        PopulateDropdowns(timeValue.StocksId);
        return View(timeValue);
        }

        // GET: TimeValues/Delete/5
    public async Task<IActionResult> Delete(long? id)
    {
        if (id is null) return NotFound();

        var timeValue = await _context.TimeValues
                .Include(t => t.Stocks)
                .FirstOrDefaultAsync(t => t.Id == id);

        if (timeValue is null) return NotFound();

        return View(timeValue);
    }

    // POST: TimeValues/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(long id)
    {
        var timeValue = await _context.TimeValues.FindAsync(id);
        if (timeValue is not null)
            _context.TimeValues.Remove(timeValue);

        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    // ── Helpers ──────────────────────────────────────────────────────────────

    private void PopulateDropdowns(object? selectedStock = null)
    {
        ViewBag.StockId = new SelectList(
            _context.Stocks.OrderBy(s => s.Title),
            "Id", "Title",
            selectedStock);
    }

    private bool TimeValueExists(long id) =>
        _context.TimeValues.Any(e => e.Id == id);
}
