import { BadRequestException, Body, Controller, Get, Headers, Param, Post, Query } from '@nestjs/common';
import { IiosAiJobType } from '@prisma/client';
import { AiJobService } from './ai.service';
import { SessionVerifier } from '../platform/session.verifier';
import type { MessagePrincipal } from '../identity/actor.resolver';
import { RunJobDto } from './ai.dto';

@Controller('v1/ai')
export class AiController {
  constructor(
    private readonly ai: AiJobService,
    private readonly session: SessionVerifier,
  ) {}

  @Post('jobs')
  async runJob(@Body() body: RunJobDto, @Headers('authorization') auth?: string) {
    return this.ai.runJob({
      interactionId: body.interactionId,
      jobType: body.jobType as IiosAiJobType,
      principal: this.principal(auth),
    });
  }

  @Get('artifacts')
  async listArtifacts(
    @Query('interactionId') interactionId?: string,
    @Query('status') status?: string,
    @Headers('authorization') auth?: string,
  ) {
    return this.ai.listArtifacts(this.principal(auth), { interactionId, status });
  }

  @Get('artifacts/:id')
  async getArtifact(@Param('id') id: string, @Headers('authorization') auth?: string) {
    return this.ai.getArtifact(id, this.principal(auth));
  }

  @Post('artifacts/:id/accept')
  async accept(@Param('id') id: string, @Headers('authorization') auth?: string) {
    return this.ai.accept(id, this.principal(auth));
  }

  @Post('artifacts/:id/reject')
  async reject(@Param('id') id: string, @Headers('authorization') auth?: string) {
    return this.ai.reject(id, this.principal(auth));
  }

  private principal(authorization?: string): MessagePrincipal {
    const token = (authorization ?? '').replace(/^Bearer\s+/i, '');
    if (!token) throw new BadRequestException('Authorization bearer token is required');
    return this.session.verify(token);
  }
}
