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

import mx.gob.slp.baseadminweb.configuration.security.ApiAuthService;
import mx.gob.slp.baseadminweb.configuration.security.ApiLoginResponse;
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.LinkedHashMap;
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 {
            ApiLoginResponse response = apiAuthService.login(request.username(), request.password());
            return ResponseEntity.ok(toAuthBody(response));
        } catch (BadCredentialsException ex) {
            return unauthorized(ex.getMessage());
        }
    }

    @PostMapping("/refresh")
    public ResponseEntity<?> refresh(@RequestBody RefreshRequest request) {
        try {
            ApiLoginResponse response = apiAuthService.refresh(request.refreshToken());
            return ResponseEntity.ok(toAuthBody(response));
        } catch (BadCredentialsException ex) {
            return unauthorized(ex.getMessage());
        }
    }

    private Map<String, Object> toAuthBody(ApiLoginResponse response) {
        Map<String, Object> body = new LinkedHashMap<>();
        body.put("success", true);
        body.put("accessToken", response.accessToken());
        body.put("refreshToken", response.refreshToken());
        body.put("idToken", response.idToken());
        body.put("tokenType", response.tokenType());
        body.put("expiresIn", response.expiresIn());
        body.put("username", response.username());
        body.put("roles", response.roles());
        return body;
    }

    private ResponseEntity<Map<String, Object>> unauthorized(String message) {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of(
                "success", false,
                "message", message
        ));
    }

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

    public record RefreshRequest(String refreshToken) {
    }
}