package com.example.FinanceTracker.Controllers;

import java.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
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.Models.Transaction;
import com.example.FinanceTracker.Services.TransactionService;

@Controller
public class TransactionsController {

    @Autowired
    private TransactionService transactionService;

    // Main Page Load
    @GetMapping("/transactions")
    public String transactions(
            Model model,
            @RequestParam(defaultValue = "0") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {

        prepareModel(model, "", pageNum, pageSize);
        model.addAttribute("footerDetails", "Copyright © FinanceTracker " + LocalDate.now().getYear());
        return "transactions";
    }

    @GetMapping({ "/transactions-fragment", "/searchTransactions" })
    public String getTransactionsFragment(
            Model model,
            @RequestParam(value = "searchValue", required = false, defaultValue = "") String searchValue,
            @RequestParam(defaultValue = "0") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {

        prepareModel(model, searchValue, pageNum, pageSize);
        // Returns only the specific fragment inside transactions.html
        return "transactions :: transactionList";
    }

    private void prepareModel(Model model, String search, int page, int size) {
        Page<Transaction> results;
        if (search == null || search.isBlank()) {
            results = transactionService.findAllPaged(page, size);
        } else {
            results = transactionService.searchTransactions(search, page, size);
        }

        model.addAttribute("transactions", results.getContent());
        model.addAttribute("pageNum", page);
        model.addAttribute("totalPages", results.getTotalPages());
        model.addAttribute("searchValue", search);
        model.addAttribute("pageSize", size);
    }

}
