package de.avatic.lcc.controller.token;

import de.avatic.lcc.model.db.users.App;
import de.avatic.lcc.service.apps.JwtTokenService;
import de.avatic.lcc.service.apps.AppsService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/oauth2/token")
public class TokenController {

    private final JwtTokenService jwtTokenService;

    private final AppsService appService;

    public TokenController(JwtTokenService jwtTokenService, AppsService appService) {
        this.jwtTokenService = jwtTokenService;
        this.appService = appService;
    }

    @PostMapping({"/", ""})
    public ResponseEntity<?> issueToken(
            @RequestParam("grant_type") String grantType,
            @RequestParam("client_id") String clientId,
            @RequestParam("client_secret") String clientSecret,
            @RequestParam(value = "scope", required = false) String scope) {

        long expiration = 3600;

        if (!"client_credentials".equals(grantType)) {
            return ResponseEntity.badRequest()
                    .body(Map.of("error", "unsupported_grant_type"));
        }

        Optional<App> app = appService.validateApp(clientId, clientSecret);
        if (app.isEmpty()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(Map.of("error", "invalid_client"));
        }

        String token = jwtTokenService.createApplicationToken(app.get(), expiration);

        return ResponseEntity.ok(Map.of(
                "access_token", token,
                "token_type", "Bearer",
                "expires_in", expiration
        ));
    }
}