import { Controller, Get, Param, Post, Query, Req, UseGuards } from '@nestjs/common'
import { ActorService } from '../auth/actor.service.js'
import { clientIp } from '../auth/client-ip.js'
import { CurrentUser } from '../auth/current-user.decorator.js'
import type { AuthentikJwtPayload } from '../auth/jwt-payload.interface.js'
import { JwtAuthGuard } from '../auth/jwt-auth.guard.js'
import { OperatorGuard } from '../auth/operator.guard.js'
import { BillingService } from './billing.service.js'

// Platform-wide billing reads + payout-ledger generation. Operator-only.
@Controller('billing')
@UseGuards(JwtAuthGuard, OperatorGuard)
export class OperatorBillingController {
  constructor(
    private readonly billing: BillingService,
    private readonly actor: ActorService,
  ) {}

  @Get('summary')
  summary() {
    return this.billing.platformSummary()
  }

  @Get('invoices')
  invoices() {
    return this.billing.platformInvoices()
  }

  @Get('tenants/:slug/invoices')
  tenantInvoices(@Param('slug') slug: string) {
    return this.billing.tenantInvoicesBySlug(slug)
  }

  // Full partner-cut ledger across all partners (most recent month first).
  @Get('payouts')
  payouts() {
    return this.billing.platformPayouts()
  }

  // Force a payout-ledger generation run. Optional ?period=YYYY-MM (defaults to
  // the current month). Idempotent; never rewrites a row already marked paid.
  @Post('payouts/generate')
  async generatePayouts(
    @CurrentUser() jwt: AuthentikJwtPayload,
    @Req() req: Parameters<typeof clientIp>[0],
    @Query('period') period?: string,
  ) {
    const user = await this.actor.resolve(jwt)
    return this.billing.generatePayouts(period, {
      userId: user._id,
      email: user.email,
      ip: clientIp(req),
    })
  }
}
