import {
  Controller,
  Post,
  Get,
  Param,
  Body,
  HttpCode,
  ParseIntPipe,
} from '@nestjs/common';
import { BillingService } from './billing.service';

/**
 * ADMIN / SUPERADMIN billing controls.
 *
 * Mounted under `companies` so the project's global PermissionGuard protects it
 * exactly like the existing /companies/:id/portal-users admin routes:
 *   - staff with `companies` permission  → allowed
 *   - clients (no staff permission)      → blocked (403)
 *
 * To restrict to superadmin ONLY, add a @RequirePermission(...) decorator or a
 * role check — see the note in the chat.
 */
@Controller('companies')
export class BillingAdminController {
  constructor(private readonly billing: BillingService) {}

  /** GET /api/companies/:companyId/billing — current subscription + admin-set price */
  @Get(':companyId/billing')
  @HttpCode(200)
  async status(@Param('companyId', ParseIntPipe) companyId: number) {
    return { success: true, data: await this.billing.getStatus(companyId) };
  }

  /**
   * POST /api/companies/:companyId/billing/set-price
   * body: { amount: number (minor units), currency?: 'aed', interval?: 'year'|'month'|'one_time' }
   */
  @Post(':companyId/billing/set-price')
  @HttpCode(200)
  async setPrice(
    @Param('companyId', ParseIntPipe) companyId: number,
    @Body() body: { amount: number; currency?: string; interval?: string },
  ) {
    return {
      success: true,
      data: await this.billing.setCompanyPrice(
        companyId,
        Number(body?.amount),
        body?.currency,
        body?.interval,
      ),
    };
  }

  /** POST /api/companies/:companyId/billing/grant-free — free access, no charge */
  @Post(':companyId/billing/grant-free')
  @HttpCode(200)
  async grantFree(@Param('companyId', ParseIntPipe) companyId: number) {
    return { success: true, data: await this.billing.grantFreeAccess(companyId) };
  }

  /** POST /api/companies/:companyId/billing/mark-paid — offline/manual payment */
  @Post(':companyId/billing/mark-paid')
  @HttpCode(200)
  async markPaid(@Param('companyId', ParseIntPipe) companyId: number) {
    return { success: true, data: await this.billing.markPaidManually(companyId) };
  }

  /** POST /api/companies/:companyId/billing/revoke — cancel access (paywall returns) */
  @Post(':companyId/billing/revoke')
  @HttpCode(200)
  async revoke(@Param('companyId', ParseIntPipe) companyId: number) {
    return { success: true, data: await this.billing.revokeAccess(companyId) };
  }
}
