import { Body, Controller, Get, HttpCode, HttpStatus, Post, UseGuards } from "@nestjs/common";
import {
  AddProviderDto,
  ConfigureOidcDto,
  CreateBreakglassDto,
  TestProviderDto,
} from "./onboarding.dto";
import { OnboardingGuard } from "./onboarding.guard";
import { OnboardingService } from "./onboarding.service";

@Controller("onboarding")
export class OnboardingController {
  constructor(private readonly onboardingService: OnboardingService) {}

  // GET /api/onboarding/status — returns { completed: boolean }
  @Get("status")
  async status(): Promise<{ completed: boolean }> {
    return {
      completed: await this.onboardingService.isCompleted(),
    };
  }

  // POST /api/onboarding/breakglass — body: { username, password } → create admin
  @Post("breakglass")
  @UseGuards(OnboardingGuard)
  async createBreakglass(
    @Body() body: CreateBreakglassDto
  ): Promise<{ id: string; username: string }> {
    return this.onboardingService.createBreakglassUser(body.username, body.password);
  }

  // POST /api/onboarding/oidc — body: { issuerUrl, clientId, clientSecret } → save OIDC
  @Post("oidc")
  @UseGuards(OnboardingGuard)
  @HttpCode(HttpStatus.NO_CONTENT)
  async configureOidc(@Body() body: ConfigureOidcDto): Promise<void> {
    await this.onboardingService.configureOidc(body.issuerUrl, body.clientId, body.clientSecret);
  }

  // POST /api/onboarding/provider — body: { name, displayName, type, baseUrl?, apiKey?, models? } → add provider
  @Post("provider")
  @UseGuards(OnboardingGuard)
  async addProvider(@Body() body: AddProviderDto): Promise<{ id: string }> {
    const userId = await this.onboardingService.getBreakglassUserId();

    return this.onboardingService.addProvider(userId, body);
  }

  // POST /api/onboarding/provider/test — body: { type, baseUrl?, apiKey? } → test connection
  @Post("provider/test")
  @UseGuards(OnboardingGuard)
  async testProvider(@Body() body: TestProviderDto): Promise<{ success: boolean; error?: string }> {
    return this.onboardingService.testProvider(body.type, body.baseUrl, body.apiKey);
  }

  // POST /api/onboarding/complete — mark done
  @Post("complete")
  @UseGuards(OnboardingGuard)
  @HttpCode(HttpStatus.NO_CONTENT)
  async complete(): Promise<void> {
    await this.onboardingService.complete();
  }
}
