import {
  Body,
  Controller,
  ForbiddenException,
  Get,
  Param,
  Post,
  Put,
  Req,
  UseGuards,
} from '@nestjs/common';
import { AllowAuth } from '../common/decorators/allow-auth.decorator';
import { ServiceCredentialGuard } from '../common/guards/service-credential/service-credential.guard';
import { LaravelIdentityService } from '../common/services/laravel-identity.service';
import { AtlasProxyService } from './atlas-proxy.service';

/**
 * AtlasProxyController forwards web-app requests to Atlas, presenting the
 * BFF's scoped service key. Because that key is privileged, every mutating
 * route derives the caller identity from Laravel (/v1/me) and refuses to act
 * on anyone else's records (confused-deputy guard).
 */
@Controller('atlas')
@AllowAuth(['user_jwt', 'client_jwt'])
@UseGuards(ServiceCredentialGuard)
export class AtlasProxyController {
  constructor(
    private readonly atlasProxyService: AtlasProxyService,
    private readonly identity: LaravelIdentityService,
  ) {}

  /** Resolve the planner identity behind the token, fail closed. */
  private async requireMe(
    req: any,
  ): Promise<{ uuid?: string; stripe_id?: string }> {
    const token = req.user?.rawToken;
    const me = token ? await this.identity.resolveMe(token) : null;
    if (!me?.stripe_id) {
      throw new ForbiddenException(
        'Não foi possível verificar a identidade do usuário.',
      );
    }
    return me;
  }

  @Get('platform-videos')
  async getPlatformVideos() {
    return this.atlasProxyService.forwardRequest('GET', '/platform-videos');
  }

  @Put('clients/:stripeId')
  @AllowAuth(['user_jwt'])
  async updateClient(
    @Param('stripeId') stripeId: string,
    @Body() body: unknown,
    @Req() req: any,
  ) {
    const me = await this.requireMe(req);
    if (stripeId !== me.stripe_id) {
      throw new ForbiddenException(
        'Você só pode atualizar o seu próprio cadastro.',
      );
    }
    return this.atlasProxyService.forwardRequest(
      'PUT',
      `/clients/${encodeURIComponent(me.stripe_id)}`,
      body,
    );
  }

  @Post('clients/onboarding-business')
  @AllowAuth(['user_jwt'])
  async onboardingBusiness(
    @Body() body: Record<string, unknown>,
    @Req() req: any,
  ) {
    const me = await this.requireMe(req);
    return this.atlasProxyService.forwardRequest(
      'POST',
      '/clients/onboarding-business',
      {
        ...(body ?? {}),
        stripeId: me.stripe_id, // identity comes from the token, not the client
        customerApiUuid: me.uuid,
      },
    );
  }
}
