import type { ListUsersInput } from '@core/admin/application/use-cases/ListUsersUseCase';
import { Controller, Get, Inject, Query, Req, UseGuards } from '@nestjs/common';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import type { Request } from 'express';
import { AuthorizationGuard } from '../auth/AuthorizationGuard';
import { RequireAuthenticatedUser } from '../auth/RequireAuthenticatedUser';
import { RequireRoles } from '../auth/RequireRoles';
import { AdminService } from './AdminService';
import { DashboardStatsResponseDto } from './dto/DashboardStatsResponseDto';
import { ListUsersRequestDto } from './dtos/ListUsersRequestDto';
import { UserListResponseDto } from './dtos/UserResponseDto';

@ApiTags('admin')
@Controller('admin')
@UseGuards(AuthorizationGuard)
export class AdminController {
  constructor(
    @Inject(AdminService) private readonly adminService: AdminService,
  ) {}

  @Get('users')
  @RequireAuthenticatedUser()
  @RequireRoles('owner', 'admin')
  @ApiOperation({ summary: 'List all users (Owner/Super Admin only)' })
  @ApiResponse({ status: 200, description: 'List of users', type: UserListResponseDto })
  @ApiResponse({ status: 403, description: 'Forbidden - not a system admin' })
  async listUsers(
    @Query() query: ListUsersRequestDto,
    @Req() req: Request,
  ): Promise<UserListResponseDto> {
    // Get actorId from request (will be set by auth middleware/guard)
    const actorId = (req as Request & { user?: { userId?: string } }).user?.userId || 'current-user';
    
    // Build input with only defined values
    const input: ListUsersInput = {
      actorId,
      page: query.page || 1,
      limit: query.limit || 10,
    };

    if (query.role !== undefined) input.role = query.role;
    if (query.status !== undefined) input.status = query.status;
    if (query.email !== undefined) input.email = query.email;
    if (query.search !== undefined) input.search = query.search;
    if (query.sortBy !== undefined) input.sortBy = query.sortBy;
    if (query.sortDirection !== undefined) input.sortDirection = query.sortDirection;

    return await this.adminService.listUsers(input);
  }

  @Get('dashboard/stats')
  @RequireAuthenticatedUser()
  @RequireRoles('owner', 'admin')
  @ApiOperation({ summary: 'Get dashboard statistics (Owner/Super Admin only)' })
  @ApiResponse({ status: 200, description: 'Dashboard statistics', type: DashboardStatsResponseDto })
  @ApiResponse({ status: 403, description: 'Forbidden - not a system admin' })
  async getDashboardStats(
    @Req() req: Request,
  ): Promise<DashboardStatsResponseDto> {
    // Get actorId from request (will be set by auth middleware/guard)
    const actorId = (req as Request & { user?: { userId?: string } }).user?.userId || 'current-user';
    
    const input = { actorId };

    return await this.adminService.getDashboardStats(input);
  }
}