import { Body, Controller, Get, Put, Request } from '@nestjs/common';
import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';

import { SignaturesService } from './signatures.service';
import { SaveSignatureDto, SavedSignatureDto } from './dto/save-signature.dto';

@ApiTags('Signatures')
@Controller('me/signature')
export class SignaturesController {
  constructor(private readonly signaturesService: SignaturesService) {}

  @Get()
  @ApiOkResponse({ type: SavedSignatureDto })
  @ApiOperation({ summary: "Current user's reusable saved signature" })
  getMySignature(
    @Request() req: { user?: { id?: string; sub?: string } },
  ): Promise<SavedSignatureDto | null> {
    const userId = req.user?.id ?? req.user?.sub;
    if (!userId) return Promise.resolve(null);
    return this.signaturesService.getForUser(userId);
  }

  @Put()
  @ApiOkResponse({ type: SavedSignatureDto })
  @ApiOperation({ summary: 'Create or update the reusable saved signature' })
  async saveMySignature(
    @Body() dto: SaveSignatureDto,
    @Request() req: { user?: { id?: string; sub?: string } },
  ): Promise<SavedSignatureDto | null> {
    const userId = req.user?.id ?? req.user?.sub;
    if (!userId) return null;
    await this.signaturesService.upsertForUser({
      userId,
      signerDisplayName: dto.signerDisplayName,
      signatureImageBase64: dto.signatureImageBase64,
    });
    return this.signaturesService.getForUser(userId);
  }
}
