package com.platform2easy.genesis.web.controller;

import com.platform2easy.genesis.domain.model.AppUser;
import com.platform2easy.genesis.domain.repository.AppUserRepository;
import com.platform2easy.genesis.domain.service.UserService;
import com.platform2easy.genesis.infra.security.TokenService;
import com.platform2easy.genesis.web.dto.AuthenticationDTO;
import com.platform2easy.genesis.web.dto.RegisterDTO;
import com.platform2easy.genesis.web.dto.TokenDTO;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@RestController("webAuthenticationController")
@RequestMapping("/auth")
public class AuthenticationController {

    private final UserService service;
    private final AppUserRepository appUserRepository;
    private final PasswordEncoder passwordEncoder;
    private final TokenService tokenService;

    public AuthenticationController(AppUserRepository appUserRepository, PasswordEncoder passwordEncoder, TokenService tokenService) {
        this.appUserRepository = appUserRepository;
        this.passwordEncoder = passwordEncoder;
        this.tokenService = tokenService;
    }

    // GET /api/auth/{companyId}: Busca por ID da Empresa
    @GetMapping("/{companyId}")
    @ResponseStatus(HttpStatus.OK)
    public AppUser getByCompanyId(@PathVariable Integer companyId) {
        return service.buscarPorEmpresa(companyId);
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@Valid @RequestBody RegisterDTO dto) {
        Optional<AppUser> existing = appUserRepository.findByUserEmail(dto.getEmail());
        if (existing.isPresent()) {
            return ResponseEntity.status(HttpStatus.CONFLICT).build();
        }
        AppUser user = new AppUser();
        user.setUserName(dto.getName());
        user.setUserEmail(dto.getEmail());
        user.setUserPassword(passwordEncoder.encode(dto.getPassword()));
        user.setUserPhone(dto.getPhone());
        user.setUserAddress(dto.getAddress());
        user.setUserCity(dto.getCity());
        user.setUserState(dto.getState());
        user.setUserZip(dto.getZip());
        user.setUserCountry(dto.getCountry());
        user.setUserKyc(dto.getKyc());
        user.setUserBirthdate(dto.getBirthdate());
        user.setUserCpf(dto.getCpf());
        user.setCompanyId(dto.getCompanyId());
        user.setRoleId(dto.getRoleId());
        user.setUserFlag(dto.getFlag());
        AppUser saved = appUserRepository.save(user);
        String token = tokenService.generateToken(saved);
        return ResponseEntity.status(HttpStatus.CREATED).body(new TokenDTO(token));
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@Valid @RequestBody AuthenticationDTO dto) {
        Optional<AppUser> existing = appUserRepository.findByUserEmail(dto.getEmail());
        if (existing.isEmpty()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        AppUser user = existing.get();
        if (!passwordEncoder.matches(dto.getPassword(), user.getUserPassword())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        String token = tokenService.generateToken(user);
        return ResponseEntity.ok(new TokenDTO(token));
    }

    @PostMapping("/register/default")
    public ResponseEntity<?> registerDefault() {
        final String email = "tester@tooeasy.local";
        final String rawPassword = "ChangeMe123!";

        Optional<AppUser> existing = appUserRepository.findByUserEmail(email);
        AppUser user;
        HttpStatus status;
        if (existing.isPresent()) {
            user = existing.get();
            status = HttpStatus.OK;
        } else {
            user = new AppUser();
            user.setUserName("Tester");
            user.setUserEmail(email);
            user.setUserPassword(passwordEncoder.encode(rawPassword));
            user.setUserPhone("0000000000");
            user.setUserAddress("N/A");
            user.setUserCity("N/A");
            user.setUserState("NA");
            user.setUserZip("00000");
            user.setUserCountry("BR");
            user.setUserKyc(1);
            user.setUserBirthdate(19900101);
            user.setUserCpf("00000000000");
            user.setCompanyId(1);
            user.setRoleId(1);
            user.setUserFlag("ACTIVE");
            user = appUserRepository.save(user);
            status = HttpStatus.CREATED;
        }
        String token = tokenService.generateToken(user);
        return ResponseEntity.status(status).body(new TokenDTO(token));
    }

    // PUT /api/auth/register/{id}: Atualiza um registro existente
    @PutMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    public AppUser update(@PathVariable Long id, @RequestBody AppUser user) {
        user.setId(id);
        return service.salvar(user);
    }

    // DELETE /api/auth/register/{id}: Deleta um registro
    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable Long id) {
        service.deletarPorId(id);
    }
}
