import {
  Controller,
  Post,
  UseGuards,
  Get,
  Param,
  BadRequestException,
} from '@nestjs/common';
import { StripeService } from './stripe.service';
import { UserAuthGuard } from 'src/users/auth/user.auth.guard';
import { UserDecorator } from 'src/common/decorator';

@Controller('stripe')
export class StripeController {
  constructor(private readonly stripeService: StripeService) {}

  @UseGuards(UserAuthGuard)
  @Post('connect')
  async connect(@UserDecorator() user: any) {
    // 1️⃣ Create or reuse Stripe account (always returns string)
    const accountId = await this.stripeService.createConnectAccount(user._id);

    // 2️⃣ Generate onboarding link
    const link = await this.stripeService.createOnboardingLink(accountId);

    // 3️⃣ Return URL
    return {
      url: link.url,
    };
  }

  @UseGuards(UserAuthGuard)
  @Post('disconnect')
  async disconnectStripe(@UserDecorator() user: any) {
    if (!user) {
      throw new BadRequestException('User account not connected');
    }

    await this.stripeService.disconnectAccount(user._id);

    return {
      success: true,
      message: 'Stripe disconnected successfully',
    };
  }

  /**
   * Called after Stripe onboarding redirect
   */
  @Get('account-status/:accountId')
  async getAccountStatus(@Param('accountId') accountId: string) {
    return this.stripeService.getAccountStatusByAccountId(accountId);
  }

  @Post('checkout/:invoiceId')
  async checkout(@Param('invoiceId') invoiceId: string) {
    return this.stripeService.createCheckoutSession(invoiceId);
  }
}
