package ru.kirillius.pf.sdn.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ru.kirillius.pf.sdn.dto.ApiTokenResponse;
import ru.kirillius.pf.sdn.dto.CreateApiTokenRequest;
import ru.kirillius.pf.sdn.dto.ErrorResponse;
import ru.kirillius.pf.sdn.service.AuthService;
import ru.kirillius.pf.sdn.service.SessionService;

import java.util.List;

@RestController
@RequestMapping("/api/tokens")
@RequiredArgsConstructor
public class ApiTokenController {

    private final AuthService authService;
    private final SessionService sessionService;

    @PostMapping
    public ResponseEntity<?> create(
            @RequestHeader("Authorization") String authHeader,
            @RequestBody CreateApiTokenRequest request) {

        var maybeUserId = sessionService.resolveUserId(authHeader);
        if (maybeUserId.isEmpty()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(new ErrorResponse("Invalid or missing token"));
        }

        if (request.getName() == null || request.getName().isBlank()) {
            return ResponseEntity.badRequest()
                    .body(new ErrorResponse("Name is required"));
        }

        String rawToken = authService.generateApiToken(maybeUserId.get(), request.getName().trim());
        return ResponseEntity.ok(new ApiTokenResponse(null, request.getName().trim(), rawToken, true, null, null));
    }

    @GetMapping
    public ResponseEntity<?> list(@RequestHeader("Authorization") String authHeader) {
        var maybeUserId = sessionService.resolveUserId(authHeader);
        if (maybeUserId.isEmpty()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(new ErrorResponse("Invalid or missing token"));
        }

        var tokens = authService.getUserApiTokens(maybeUserId.get()).stream()
                .map(t -> new ApiTokenResponse(t.getId(), t.getName(), null, t.isEnabled(), t.getCreatedAt(), t.getLastUsedAt()))
                .toList();
        return ResponseEntity.ok(tokens);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> delete(
            @RequestHeader("Authorization") String authHeader,
            @PathVariable Long id) {

        var maybeUserId = sessionService.resolveUserId(authHeader);
        if (maybeUserId.isEmpty()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(new ErrorResponse("Invalid or missing token"));
        }

        boolean deleted = authService.deleteApiToken(id, maybeUserId.get());
        if (!deleted) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ErrorResponse("Token not found"));
        }

        return ResponseEntity.noContent().build();
    }
}
