package mx.gob.slp.baseadminweb.web.controller;

import mx.gob.slp.baseadminweb.application.service.PassCodeService;
import mx.gob.slp.baseadminweb.web.dto.PassCodeListItem;
import mx.gob.slp.baseadminweb.web.support.WebUserView;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/admin/pass-codes")
public class PassCodeController {

    private final PassCodeService passCodeService;

    public PassCodeController(PassCodeService passCodeService) {
        this.passCodeService = passCodeService;
    }

    @GetMapping
    public String list(Authentication authentication, Model model) {
        model.addAttribute("user", WebUserView.from(authentication));
        model.addAttribute("passCodes", passCodeService.findAll());
        return "pass-codes";
    }

    @GetMapping("/list")
    @ResponseBody
    public List<PassCodeListItem> listJson() {
        return passCodeService.findAll().stream()
                .map(PassCodeListItem::from)
                .toList();
    }

    @PostMapping
    public String create(@RequestParam String name, RedirectAttributes redirectAttributes) {
        try {
            var created = passCodeService.create(name);
            redirectAttributes.addFlashAttribute("successMessage",
                    "Codigo pase creado: " + created.getCode());
        } catch (RuntimeException ex) {
            redirectAttributes.addFlashAttribute("errorMessage", ex.getMessage());
        }
        return "redirect:/admin/pass-codes";
    }
}