package com.pandoli365.bibimbap.controller;

import com.pandoli365.bibimbap.data.JamAwardData;
import com.pandoli365.bibimbap.data.JamData;
import com.pandoli365.bibimbap.mapper.JamAwardsMapper;
import com.pandoli365.bibimbap.mapper.JamsMapper;
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 java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Controller
public class JamAwardController {

    private final JamsMapper jamsMapper;
    private final JamAwardsMapper jamAwardsMapper;

    public JamAwardController(JamsMapper jamsMapper, JamAwardsMapper jamAwardsMapper) {
        this.jamsMapper = jamsMapper;
        this.jamAwardsMapper = jamAwardsMapper;
    }

    @GetMapping("/jams/{slug}/results")
    public String results(@PathVariable("slug") String slug, Model model) {
        JamData jam = jamsMapper.getBySlug(slug);
        if (jam == null || Boolean.FALSE.equals(jam.getIsVisible())) {
            return "redirect:/jams";
        }

        List<JamAwardData> awards = jamAwardsMapper.listByJamWithGame(jam.getId());
        Map<String, List<JamAwardData>> byTrack = new LinkedHashMap<>();
        for (JamAwardData award : awards) {
            byTrack.computeIfAbsent(award.getAwardTrack(), track -> new ArrayList<>()).add(award);
        }

        model.addAttribute("jam", jam);
        model.addAttribute("byTrack", byTrack);
        model.addAttribute("grand", byTrack.getOrDefault("GRAND", List.of()));
        return "jam-results";
    }
}
