package com.weighttracker.controller;

import com.weighttracker.model.WeightRecord;
import com.weighttracker.model.User;
import com.weighttracker.repository.UserRepository;
import com.weighttracker.service.WeightService;
import jakarta.validation.Valid;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Controller
@RequestMapping("/registros")
public class WeightController {

    private final WeightService weightService;
    private final UserRepository userRepo;

    public WeightController(WeightService weightService, UserRepository userRepo) {
        this.weightService = weightService;
        this.userRepo = userRepo;
    }

    /* ---------- listado ---------- */
    @GetMapping
    public String list(@AuthenticationPrincipal UserDetails ud, Model model) {
        User u = userRepo.findByUsername(ud.getUsername()).orElseThrow();
        model.addAttribute("registros", weightService.findByUser(u));
        return "registros";
    }

    /* ---------- nuevo ---------- */
    @GetMapping("/nuevo")
    public String nuevo(Model model) {
        WeightRecord wr = new WeightRecord();
        wr.setDate(LocalDateTime.now());
        model.addAttribute("registro", wr);
        return "registro-form";
    }

    @PostMapping("/guardar")
    public String guardar(@AuthenticationPrincipal UserDetails ud,
            @ModelAttribute("registro") @Valid WeightRecord wr) {
        wr.setUser(userRepo.findByUsername(ud.getUsername()).orElseThrow());
        weightService.save(wr);
        return "redirect:/registros";
    }

    /* ---------- editar ---------- */
    @GetMapping("/{id}/editar")
    public String editar(@PathVariable Long id, Model model) {
        model.addAttribute("registro", weightService.findById(id));
        return "registro-form";
    }

    @PostMapping("/{id}/eliminar")
    public String eliminar(@PathVariable Long id, @AuthenticationPrincipal UserDetails ud) {
        User user = userRepo.findByUsername(ud.getUsername()).orElseThrow();
        WeightRecord record = weightService.findById(id);

        // Solo permite borrar si es el dueño o si es ADMIN
        if (record.getUser().getId().equals(user.getId()) || user.getRole().equals("ADMIN")) {
            weightService.deleteById(id);
        }

        return "redirect:/registros";
    }
}