package com.example.equipment.controller;

import com.example.equipment.model.Equipment;
import com.example.equipment.service.EquipmentService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 備品画面コントローラ（Thymeleaf）
 */
@Controller
public class EquipmentController {

    private final EquipmentService equipmentService;

    public EquipmentController(EquipmentService equipmentService) {
        this.equipmentService = equipmentService;
    }

    /** トップは一覧へ */
    @GetMapping("/")
    public String index() {
        return "redirect:/equipments";
    }

    /** 一覧と検索 */
    @GetMapping("/equipments")
    public String list(@RequestParam(name = "keyword", required = false) String keyword,
                       Model model) {
        List<Equipment> equipments = equipmentService.searchByName(keyword);

        Map<Long, String> purchaseDates = new HashMap<>();
        Map<Long, Boolean> lowStockFlags = new HashMap<>();
        for (Equipment equipment : equipments) {
            purchaseDates.put(equipment.getId(),
                    equipmentService.formatPurchaseDateForList(equipment));
            lowStockFlags.put(equipment.getId(),
                    equipmentService.isLowStock(equipment));
        }

        model.addAttribute("equipments", equipments);
        model.addAttribute("purchaseDates", purchaseDates);
        model.addAttribute("lowStockFlags", lowStockFlags);
        model.addAttribute("keyword", keyword);
        return "list";
    }

    /** 詳細 */
    @GetMapping("/equipments/{id}")
    public String detail(@PathVariable Long id, Model model) {
        Equipment equipment = equipmentService.findById(id);
        model.addAttribute("equipment", equipment);
        model.addAttribute("purchaseDate",
                equipmentService.formatPurchaseDateForDetail(equipment));
        model.addAttribute("noteSummary",
                equipmentService.buildNoteSummary(equipment));
        model.addAttribute("lowStock", equipmentService.isLowStock(equipment));
        return "detail";
    }

    /** 貸出（在庫を減らす） */
    @PostMapping("/equipments/{id}/lend")
    public String lend(@PathVariable Long id,
                       @RequestParam(name = "quantity", defaultValue = "1") int quantity) {
        equipmentService.lend(id, quantity);
        return "redirect:/equipments/" + id;
    }
}
