package com.example.demo;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.cornutum.regexpgen.RandomGen;
import org.cornutum.regexpgen.RegExpGen;
import org.cornutum.regexpgen.js.Provider;
import org.cornutum.regexpgen.random.RandomBoundsGen;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.RequestParam;

@Controller
public class LoginController {
    private final SessionRepository sessionRepository;
    private String username;
    private String password;

    @Autowired
    public LoginController(SessionRepository sessionRepository, @Value("${app.username}") String username, @Value("${app.password}") String password) {
        this.sessionRepository = sessionRepository;
        this.username = username;
        this.password = password;
    }

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @PostMapping("/login")
    public String processLogin(
            @RequestParam String username,
            @RequestParam String password,
            Model model,
            HttpServletResponse response
    ) {
        if(!username.equals(this.username)) {
            model.addAttribute("error", "Incorrect username.");
        }

        if(!password.equals(this.password)) {
            model.addAttribute("error", "Incorrect password.");
        }

        RandomGen random = new RandomBoundsGen();
        RegExpGen generator = Provider.forEcmaScript().matching("^[a-zA-Z0-9]{35,70}$");
        String token = generator.generate(random);

        this.sessionRepository.save(new Session(token));
        Cookie cookie = new Cookie("crypto_question_session_token", token);
        response.addCookie(cookie);

        return "redirect:https://crypto-questions.caelus.ro/home";
    }
}
