import {
  Controller,
  Get,
  Param,
  Query,
  Req,
  HttpCode,
  UseGuards,
  ParseIntPipe,
  BadRequestException,
} from '@nestjs/common';
import type { Request } from 'express';
import { ClientAuthGuard } from '../guards/client-auth.guard';
import { ClientLoginLogService } from './client-login-log.service';

/**
 * ADMIN view of client logins for a company.
 *
 * Mounted under `companies` for the SAME reason your BillingAdminController is:
 * the project's global PermissionGuard then protects it exactly like the other
 * /companies/:id/... admin routes (staff with `companies` permission allowed,
 * clients blocked). Restrict to superadmin with @RequirePermission if you want.
 */
@Controller('companies')
export class ClientLoginLogAdminController {
  constructor(private readonly logs: ClientLoginLogService) {}

  /**
   * GET /api/companies/:companyId/client-logins?page=1&limit=25&status=failed
   */
  @Get(':companyId/client-logins')
  @HttpCode(200)
  async list(
    @Param('companyId', ParseIntPipe) companyId: number,
    @Query('page') page?: string,
    @Query('limit') limit?: string,
    @Query('status') status?: string,
  ) {
    const st =
      status === 'success' || status === 'failed'
        ? (status as 'success' | 'failed')
        : undefined;

    return {
      success: true,
      data: await this.logs.listForCompany(companyId, {
        page: page ? Number(page) : undefined,
        limit: limit ? Number(limit) : undefined,
        status: st,
      }),
    };
  }
}

/**
 * CLIENT-facing "where am I logged in from" — the logged-in client can see
 * their own recent login history/devices. Protected by ClientAuthGuard.
 */
@Controller('client-portal/security')
export class ClientLoginLogSelfController {
  constructor(private readonly logs: ClientLoginLogService) {}

  /** GET /api/client-portal/security/logins?limit=20 */
  @Get('logins')
  @UseGuards(ClientAuthGuard)
  @HttpCode(200)
  async myLogins(@Req() req: Request, @Query('limit') limit?: string) {
    const user = req.user as any;
    const clientUserId = Number(user?.sub ?? user?.id);
    if (!clientUserId || Number.isNaN(clientUserId)) {
      throw new BadRequestException('No client user in token');
    }
    return {
      success: true,
      data: await this.logs.listForClientUser(
        clientUserId,
        limit ? Number(limit) : 20,
      ),
    };
  }
}
