package com.example.chiptuningweb.controller;

import com.example.chiptuningweb.model.FullDan;
import com.example.chiptuningweb.repo.FullDanRepo;
import com.example.chiptuningweb.repo.UserChipRepo;
import com.example.chiptuningweb.service.CustomUserDetailsService;
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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class AdminController {

    @Autowired
    UserChipRepo userChipRepo;
    @Autowired
    FullDanRepo fullDanRepo;
    @Autowired
    CustomUserDetailsService userDetailsService;

    @GetMapping("/admin/token/sogjfLJFJfvjLSfjo93045ujgfdfLAdjej4/autoisation")
    public String autorisation() {
        // Проверяем, авторизован ли пользователь
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
            return "redirect:/admin/token/sogjfLJFJfvjLSfjo93045ujgfdfLAdjej4/glav";
        } else {
            return "admin/autorisation";
        }
    }

    @GetMapping("/admin/token/dfhvidhEUefhier254kHDerf/regisation")
    public String regisation() {
        return "admin/regisation";
    }

    @PostMapping("/admin/token/dfhvidhEUefhier254kHDerf/regisation")
    public String trueRegisation(@RequestParam String log, @RequestParam String pass, Model model) {
        if (userChipRepo.findByUsername(log) != null) {
            model.addAttribute("error", "Пользователь с таким логином уже существует");
        } else {
            userDetailsService.registerAdmin(log, pass);
            return "redirect:/admin/token/sogjfLJFJfvjLSfjo93045ujgfdfLAdjej4/autoisation";
        }
        return "admin/autorisation";
    }
// slfjerofFIhdf9we3rjhsif723u9rjfh


    @GetMapping("/admin/token/sogjfLJFJfvjLSfjo93045ujgfdfLAdjej4/full")
    public String glav(Model model) {
        Iterable<FullDan> posts = fullDanRepo.findAll();
        model.addAttribute("posts", posts);
        return "admin/full";
    }

}
