import { Body, Controller, Get, Param, Patch, Post, Query, Req, Res, UseGuards } from '@nestjs/common';
import { Request, Response } from 'express';
import { UserRole } from '@prisma/client';
import { PlatformService } from './platform.service';
import { CreateOrganizationDto } from './dto/create-organization.dto';
import { UpdateOrganizationDto } from './dto/update-organization.dto';
import { UpdateOrgStatusDto } from './dto/update-org-status.dto';
import { InviteOrgAdminDto } from './dto/invite-org-admin.dto';
import { ExportOrganizationsQuery } from './dto/export-organizations.query';
import { ListAuditLogsQuery } from './dto/list-audit-logs.query';
import { JwtAuthGuard } from '../../common/auth/jwt-auth.guard';
import { RolesGuard } from '../../common/auth/roles.guard';
import { Roles } from '../../common/auth/roles.decorator';
import { CurrentUser } from '../../common/auth/current-user.decorator';

@Controller('platform')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.PLATFORM_ADMIN)
export class PlatformController {
  constructor(private readonly platformService: PlatformService) {}

  // Returns list of all customer organizations/tenants. GET /api/platform/organizations
  @Get('organizations')
  async listOrganizations() {
    return this.platformService.listOrganizations();
  }

  // Exports organizations (all, or only the listed ids) to Excel (.xlsx). GET /api/platform/organizations/export
  @Get('organizations/export')
  async exportOrganizations(@Query() query: ExportOrganizationsQuery, @Res() res: Response) {
    const result = await this.platformService.exportOrganizationsExcel(query);
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', `attachment; filename="${result.filename}"`);
    res.send(result.buffer);
  }

  // Returns single organization details by tenant ID. GET /api/platform/organizations/:id
  @Get('organizations/:id')
  async getOrganization(@Param('id') id: string) {
    return this.platformService.getOrganization(id);
  }

  // Updates organization profile details (name, phone, city). PATCH /api/platform/organizations/:id
  @Patch('organizations/:id')
  async updateOrganization(@Param('id') id: string, @Body() dto: UpdateOrganizationDto, @CurrentUser('id') actorId: string, @Req() req: Request) {
    const ipAddress = req.ip || req.socket.remoteAddress;
    return this.platformService.updateOrganization(id, dto, actorId, ipAddress);
  }

  // Creates a new customer tenant organization. POST /api/platform/organizations
  @Post('organizations')
  async createOrganization(@Body() dto: CreateOrganizationDto, @CurrentUser('id') actorId: string, @Req() req: Request) {
    const ipAddress = req.ip || req.socket.remoteAddress;
    return this.platformService.createOrganization(dto, actorId, ipAddress);
  }

  // Suspends or activates an organization tenant. PATCH /api/platform/organizations/:id/status
  @Patch('organizations/:id/status')
  async updateOrganizationStatus(@Param('id') id: string, @Body() dto: UpdateOrgStatusDto, @CurrentUser('id') actorId: string, @Req() req: Request) {
    const ipAddress = req.ip || req.socket.remoteAddress;
    return this.platformService.updateOrganizationStatus(id, dto, actorId, ipAddress);
  }

  // Invites initial organization administrator for tenant. POST /api/platform/organizations/:id/invite-admin
  @Post('organizations/:id/invite-admin')
  async inviteFirstOrgAdmin(@Param('id') id: string, @Body() dto: InviteOrgAdminDto, @CurrentUser('id') actorId: string, @Req() req: Request) {
    const ipAddress = req.ip || req.socket.remoteAddress;
    return this.platformService.inviteFirstOrgAdmin(id, dto, actorId, ipAddress);
  }

  // Exports platform audit log entries to Excel spreadsheet (.xlsx). GET /api/platform/audit-logs/export
  @Get('audit-logs/export')
  async exportAuditLogs(@Res() res: Response) {
    const result = await this.platformService.exportAuditLogsExcel();
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', `attachment; filename="${result.filename}"`);
    res.send(result.buffer);
  }

  // Returns one searchable page of the full audit trail. GET /api/platform/audit-logs/page
  @Get('audit-logs/page')
  async listAuditLogPage(@Query() query: ListAuditLogsQuery) {
    return this.platformService.listAuditLogPage(query);
  }

  // Returns platform-level immutable audit log entries. GET /api/platform/audit-logs
  @Get('audit-logs')
  async listAuditLogs(@Query('limit') limit?: string) {
    return this.platformService.listAuditLogs(Number(limit) || 100);
  }
}
