import { BadRequestException, Body, Controller, Get, Headers, Param, Patch, Query } from '@nestjs/common';
import { IiosInboxState } from '@prisma/client';
import { InboxService } from './inbox.service';
import { SessionVerifier } from '../platform/session.verifier';
import { PatchInboxDto } from './inbox.dto';
import type { MessagePrincipal } from '../identity/actor.resolver';

@Controller('v1/inbox')
export class InboxController {
  constructor(
    private readonly inbox: InboxService,
    private readonly session: SessionVerifier,
  ) {}

  @Get('items')
  async list(@Headers('authorization') authorization?: string, @Query('state') state?: string) {
    return this.inbox.list(this.principal(authorization), { state: state as IiosInboxState | undefined });
  }

  @Patch('items/:id')
  async patch(
    @Param('id') id: string,
    @Body() body: PatchInboxDto,
    @Headers('authorization') authorization?: string,
  ) {
    return this.inbox.transition(id, this.principal(authorization), body.state, body.reason);
  }

  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);
  }
}
