package de.accso.flexinale.web;

import de.accso.flexinale.application.KinoService;
import de.accso.flexinale.data.model.Kino;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
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.server.ResponseStatusException;

import java.util.List;

@Controller
@Transactional
public class KinoWebController {

    @Autowired
    private KinoService kinoService;

    @GetMapping(value="/kinos")
    @PreAuthorize("hasRole('ROLE_BESUCHER')")
    @SuppressWarnings("SameReturnValue")
    public String kinos(final Model model) {
        List<Kino> kinos = kinoService.kinos();
        model.addAttribute("kinos", kinos);
        return "kinos";
    }

    @GetMapping(value="/kino/{id}")
    @PreAuthorize("hasRole('ROLE_BESUCHER')")
    @SuppressWarnings("SameReturnValue")
    public String kino(@PathVariable("id") final String id, final Model model) {
        Kino kino = kinoService.kino(id);
        if (kino == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "kino %s not available".formatted(id));
        }
        else {
            model.addAttribute("kino", kino);
            return "kino";
        }
    }
}
