import {
  Body,
  Controller,
  Get,
  Post,
  Query,
  Req,
  UseGuards,
} from '@nestjs/common';
import { ApiBearerAuth, ApiOkResponse, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
import { WalletService } from './wallet.service';
import { UserRole } from '@prisma/client';
import { RolesGuard } from '../../common/guards/roles.guard';
import { Roles } from '../../common/decorators/roles.decorator';
import { Request } from 'express';

type AuthedRequest = Request & {
  user?: { id: string; role: UserRole; shopId?: string | null };
};

@ApiTags('wallet')
@Controller('wallet')
export class WalletController {
  constructor(private readonly wallet: WalletService) {}

  @Get('summary')
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN, UserRole.SUBADMIN)
  @ApiBearerAuth('bearer')
  @ApiOkResponse({
    description: 'Wallet balance + recent transactions for current shop',
  })
  summary(@Req() req: AuthedRequest, @Query('limit') limit?: string) {
    const takeRaw = limit != null ? Number(limit) : 10;
    const take = Number.isFinite(takeRaw)
      ? Math.min(Math.max(Math.floor(takeRaw), 1), 50)
      : 10;
    return this.wallet.getWalletSummaryForShop({
      shopId: req.user!.shopId!,
      take,
    });
  }

  @Get('transactions')
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN, UserRole.SUBADMIN)
  @ApiBearerAuth('bearer')
  @ApiOkResponse({
    description: 'Wallet transaction history for current shop (paginated)',
  })
  transactions(
    @Req() req: AuthedRequest,
    @Query('page') page?: string,
    @Query('limit') limit?: string,
  ) {
    const p = page != null ? Number(page) : 1;
    const l = limit != null ? Number(limit) : 20;
    const pageNum = Number.isFinite(p) ? Math.max(1, Math.floor(p)) : 1;
    const limitNum = Number.isFinite(l)
      ? Math.min(100, Math.max(1, Math.floor(l)))
      : 20;
    return this.wallet.listWalletTransactionsForShop({
      shopId: req.user!.shopId!,
      page: pageNum,
      limit: limitNum,
    });
  }

  @Post('topup')
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN, UserRole.SUBADMIN)
  @ApiBearerAuth('bearer')
  @ApiOkResponse({
    description: 'Create an Easebuzz checkout to add money to wallet',
  })
  topup(@Req() req: AuthedRequest, @Body() body: { amountInr?: number }) {
    const origin = (req.headers?.origin ?? '').toString().trim();
    const referer = (req.headers?.referer ?? req.headers?.referrer ?? '')
      .toString()
      .trim();
    let portalPublicUrl: string | null = origin || null;
    if (!portalPublicUrl && referer) {
      try {
        portalPublicUrl = new URL(referer).origin;
      } catch {
        portalPublicUrl = null;
      }
    }
    return this.wallet.createWalletTopupCheckout({
      userId: req.user!.id,
      shopId: req.user!.shopId!,
      amountToTopupInr: body?.amountInr as any,
      portalPublicUrl,
    });
  }
}
