package fr.eni.enchere.controllers;

import fr.eni.enchere.bll.UserService;
import fr.eni.enchere.bo.UserProfil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping
    public String login(Model modele) {
        //Début cookie
        String savedUsername = "";
        String savedPassword = "";
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!authentication.getName().equals("anonymousUser")){
            return "redirect:/enchere";
        }
        modele.addAttribute("savedUsername", savedUsername);
        modele.addAttribute("savedPassword", savedPassword);
        return "security/login";
    }

    @PostMapping
    public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
        UserProfil user = userService.utilisateurByName(username);
        if (user != null && user.getPassword().equals(password)) {
            return "redirect:/enchere";
        } else {
            return "redirect:/login?error";
        }
    }
}

