import { BadRequestException, Body, Controller, Get, Headers, Param, Post } from '@nestjs/common';
import { SessionVerifier } from '../platform/session.verifier';
import type { MessagePrincipal } from '../identity/actor.resolver';
import { DsrService } from './dsr.service';
import { PlaceHoldDto } from './dsr.dto';

/**
 * Data-subject rights (P9 DSR). Tenant-scoped: every op acts within the caller's own
 * scope. Erasure is self-service (the caller erases their own subject); holds are
 * managed by the tenant's admins.
 */
@Controller('v1/dsr')
export class DsrController {
  constructor(
    private readonly dsr: DsrService,
    private readonly session: SessionVerifier,
  ) {}

  @Post('erase')
  async erase(@Headers('authorization') auth?: string) {
    return this.dsr.eraseSubject(this.principal(auth));
  }

  @Post('holds')
  async placeHold(@Body() body: PlaceHoldDto, @Headers('authorization') auth?: string) {
    return this.dsr.placeHold(this.principal(auth), { targetType: body.targetType, targetId: body.targetId, reason: body.reason, expiresAt: body.expiresAt });
  }

  @Get('holds')
  async listHolds(@Headers('authorization') auth?: string) {
    return this.dsr.listHolds(this.principal(auth));
  }

  @Post('holds/:id/release')
  async releaseHold(@Param('id') id: string, @Headers('authorization') auth?: string) {
    return this.dsr.releaseHold(this.principal(auth), id);
  }

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