import {
  Controller,
  Post,
  Get,
  Req,
  Headers,
  HttpCode,
  UseGuards,
  BadRequestException,
} from '@nestjs/common';
import type { Request } from 'express';
import { Public } from '../../common/guards/decorators/public.decorator';
import { ClientAuthGuard } from '../guards/client-auth.guard';
import { BillingService } from './billing.service';

@Controller('client-portal/billing')
export class BillingController {
  constructor(private readonly billing: BillingService) {}

  // Same pattern as ClientPortalController.getCompanyIds — picks the active company
  private getCompanyId(req: Request): number {
    const user = req.user as any;
    const all: number[] = (user?.company_ids ?? [])
      .map((n: any) => Number(n))
      .filter((n: number) => !Number.isNaN(n));
    if (!all.length) throw new BadRequestException('No company access in token');
    const header = Number((req.headers['x-company-id'] as string) ?? NaN);
    return !Number.isNaN(header) && all.includes(header) ? header : all[0];
  }

  /**
   * POST /api/client-portal/billing/create-checkout-session
   * Logged-in client starts Stripe Checkout. Returns { url } to redirect to.
   */
  @Post('create-checkout-session')
  @UseGuards(ClientAuthGuard)
  @HttpCode(200)
  async createSession(@Req() req: Request) {
    const companyId = this.getCompanyId(req);
    const user = req.user as any;
    const userId = user?.sub ?? user?.id;
    const email = user?.email;
    const data = await this.billing.createCheckoutSession(
      companyId,
      userId,
      email,
    );
    return { success: true, data };
  }

  /**
   * GET /api/client-portal/billing/status
   * Current subscription status for the client's company.
   */
  @Get('status')
  @UseGuards(ClientAuthGuard)
  @HttpCode(200)
  async status(@Req() req: Request) {
    const companyId = this.getCompanyId(req);
    const data = await this.billing.getStatus(companyId);
    return { success: true, data };
  }

  /**
   * POST /api/client-portal/billing/webhook
   * Stripe -> us. Public (no JWT), raw body, signature-verified.
   * req.rawBody is provided by the raw-body carve-out in main.ts.
   */
  @Post('webhook')
  @Public()
  @HttpCode(200)
  async webhook(
    @Req() req: any,
    @Headers('stripe-signature') signature: string,
  ) {
    const raw = req.rawBody ?? req.body;
    return this.billing.handleWebhook(raw, signature);
  }
}
