package mx.gob.slp.baseadminweb.web.controller;

import mx.gob.slp.baseadminweb.configuration.security.ApiAuthService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
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.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthApiController {

    private final ApiAuthService apiAuthService;

    public AuthApiController(ApiAuthService apiAuthService) {
        this.apiAuthService = apiAuthService;
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest request) {
        try {
            ApiAuthService.ApiLoginResponse response = apiAuthService.login(request.username(), request.password());
            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "accessToken", response.accessToken(),
                    "tokenType", response.tokenType(),
                    "expiresIn", response.expiresIn(),
                    "username", response.username(),
                    "roles", response.roles()
            ));
        } catch (BadCredentialsException ex) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of(
                    "success", false,
                    "message", ex.getMessage()
            ));
        }
    }

    public record LoginRequest(String username, String password) {
    }
}