package com.example.FinanceTracker.Controllers;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.example.FinanceTracker.DTOs.Investments.CurrRate;
import com.example.FinanceTracker.DTOs.Investments.Currency;
import com.example.FinanceTracker.DTOs.Investments.ExchangeRate;
import com.example.FinanceTracker.Services.InvestmentService;
import com.example.FinanceTracker.Services.TransactionService;

@Controller
public class InvestmentsController {

    @Autowired
    private InvestmentService investmentService;

    @Autowired
    private TransactionService transactionService;

    @GetMapping("/investments")
    public String investments(Model model) {
        // Stats and Header
        model.addAttribute("latestBalance", "Total Invested: " + transactionService.getTotalInvested() + "*");
        
        // Navigation / UI Elements
        model.addAttribute("currRates", investmentService.getCurrRates());
        model.addAttribute("allCurrencies", investmentService.getAllCurrencies());
        model.addAttribute("footerDetails", "Copyright © FinanceTracker " + LocalDate.now().getYear());

        // Default Chart Data: USD for 1 Week
        populateChartModel("USD", "WEEK", model);

        return "investments";
    }

    @GetMapping("/historicalRates")
    public String getHistoricalRates(
            @RequestParam(value = "duration", defaultValue = "WEEK") String durationCode,
            @RequestParam(value = "currencyChange", defaultValue = "USD") String currencyChange,
            Model model) {

        populateChartModel(currencyChange, durationCode, model);

        // Return only the fragment for HTMX to inject
        return "investments :: HistoricalRatesChart";
    }

    /**
     * Helper to process business logic for chart data
     */
    private void populateChartModel(String currencyCode, String durationCode, Model model) {
        int durationKey = 1;
        if ("MONTH".equals(durationCode)) durationKey = 2;
        if ("YEAR".equals(durationCode)) durationKey = 3;

        // Fetch rates and ensure they are sorted by date ascending for the chart
        List<ExchangeRate> ratesList = investmentService.getHistoricalRates(currencyCode, durationKey);
        Collections.reverse(ratesList);

        List<BigDecimal> data = new ArrayList<>();
        List<LocalDate> labels = new ArrayList<>();

        for (ExchangeRate er : ratesList) {
            data.add(er.getRate());
            labels.add(er.getCreatedAt().toLocalDate());
        }

        model.addAttribute("historicalRates", data);
        model.addAttribute("labels", labels);
    }
}