import {
  Body,
  Controller,
  Get,
  Param,
  Patch,
  Post,
  Query,
  UploadedFile,
  UseGuards,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiBearerAuth, ApiBody, ApiConsumes, ApiTags } from '@nestjs/swagger';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
import { SuperAdminPermissions } from '../../common/decorators/superadmin-permissions.decorator';
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
import { SuperAdminJwtAuthGuard } from '../../common/guards/super-admin-jwt-auth.guard';
import { SuperAdminPermissionsGuard } from '../../common/guards/superadmin-permissions.guard';
import { JwtPayload } from '../../common/interfaces/jwt-payload.interface';
import { SUPERADMIN_PERMISSIONS } from '../superadmin/superadmin-permissions';
import { AssignSupportTicketDto } from './dto/assign-support-ticket.dto';
import { CreateSupportMessageDto } from './dto/create-support-message.dto';
import { CreateSupportTicketDto } from './dto/create-support-ticket.dto';
import { SupportTicketQueryDto } from './dto/support-ticket-query.dto';
import { UpdateSupportTicketStatusDto } from './dto/update-support-ticket-status.dto';
import { SupportService } from './support.service';

type UploadFile = { mimetype?: string; size: number; buffer: Buffer; originalname?: string };

const supportImageInterceptor = FileInterceptor('image', {
  limits: { fileSize: 5 * 1024 * 1024, files: 1 },
});

@ApiTags('Support')
@Controller('support')
export class SupportController {
  constructor(private readonly supportService: SupportService) {}

  @ApiBearerAuth()
  @UseGuards(JwtAuthGuard)
  @Post('tickets')
  @UseInterceptors(supportImageInterceptor)
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    schema: {
      type: 'object',
      required: ['subject', 'message'],
      properties: {
        subject: { type: 'string', maxLength: 150 },
        message: { type: 'string', maxLength: 5000 },
        category: { type: 'string', enum: ['account', 'technical', 'media', 'payment', 'collaboration', 'other'] },
        priority: { type: 'string', enum: ['low', 'normal', 'high', 'urgent'] },
        image: { type: 'string', format: 'binary' },
      },
    },
  })
  async createTicket(
    @CurrentUser() user: JwtPayload,
    @Body() dto: CreateSupportTicketDto,
    @UploadedFile() image?: UploadFile,
  ) {
    return this.supportService.createTicket(user.sub, dto, image);
  }

  @ApiBearerAuth()
  @UseGuards(JwtAuthGuard)
  @Get('tickets')
  async myTickets(@CurrentUser() user: JwtPayload, @Query() query: SupportTicketQueryDto) {
    return this.supportService.listMyTickets(user.sub, query);
  }

  @ApiBearerAuth()
  @UseGuards(JwtAuthGuard)
  @Get('tickets/:ticketId')
  async myTicket(@CurrentUser() user: JwtPayload, @Param('ticketId') ticketId: string) {
    return this.supportService.getMyTicket(user.sub, ticketId);
  }

  @ApiBearerAuth()
  @UseGuards(JwtAuthGuard)
  @Post('tickets/:ticketId/messages')
  @UseInterceptors(supportImageInterceptor)
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        message: { type: 'string', maxLength: 5000 },
        image: { type: 'string', format: 'binary' },
      },
    },
  })
  async addUserMessage(
    @CurrentUser() user: JwtPayload,
    @Param('ticketId') ticketId: string,
    @Body() dto: CreateSupportMessageDto,
    @UploadedFile() image?: UploadFile,
  ) {
    return this.supportService.addUserMessage(user.sub, ticketId, dto, image);
  }

  @ApiBearerAuth()
  @UseGuards(JwtAuthGuard)
  @Patch('tickets/:ticketId/close')
  async closeMyTicket(@CurrentUser() user: JwtPayload, @Param('ticketId') ticketId: string) {
    return this.supportService.closeMyTicket(user.sub, ticketId);
  }

  @ApiBearerAuth()
  @UseGuards(SuperAdminJwtAuthGuard, SuperAdminPermissionsGuard)
  @SuperAdminPermissions(SUPERADMIN_PERMISSIONS.CASES_MANAGE)
  @Get('admin/tickets')
  async adminTickets(@Query() query: SupportTicketQueryDto) {
    return this.supportService.listAdminTickets(query);
  }

  @ApiBearerAuth()
  @UseGuards(SuperAdminJwtAuthGuard, SuperAdminPermissionsGuard)
  @SuperAdminPermissions(SUPERADMIN_PERMISSIONS.CASES_MANAGE)
  @Get('admin/tickets/:ticketId')
  async adminTicket(@Param('ticketId') ticketId: string) {
    return this.supportService.getAdminTicket(ticketId);
  }

  @ApiBearerAuth()
  @UseGuards(SuperAdminJwtAuthGuard, SuperAdminPermissionsGuard)
  @SuperAdminPermissions(SUPERADMIN_PERMISSIONS.CASES_MANAGE)
  @Post('admin/tickets/:ticketId/messages')
  @UseInterceptors(supportImageInterceptor)
  @ApiConsumes('multipart/form-data')
  async addAdminMessage(
    @CurrentUser() user: JwtPayload,
    @Param('ticketId') ticketId: string,
    @Body() dto: CreateSupportMessageDto,
    @UploadedFile() image?: UploadFile,
  ) {
    return this.supportService.addAdminMessage(user.sub, ticketId, dto, image);
  }

  @ApiBearerAuth()
  @UseGuards(SuperAdminJwtAuthGuard, SuperAdminPermissionsGuard)
  @SuperAdminPermissions(SUPERADMIN_PERMISSIONS.CASES_MANAGE)
  @Patch('admin/tickets/:ticketId/status')
  async updateAdminStatus(
    @Param('ticketId') ticketId: string,
    @Body() dto: UpdateSupportTicketStatusDto,
  ) {
    return this.supportService.updateAdminStatus(ticketId, dto);
  }

  @ApiBearerAuth()
  @UseGuards(SuperAdminJwtAuthGuard, SuperAdminPermissionsGuard)
  @SuperAdminPermissions(SUPERADMIN_PERMISSIONS.CASES_MANAGE)
  @Patch('admin/tickets/:ticketId/assign')
  async assignAdmin(@Param('ticketId') ticketId: string, @Body() dto: AssignSupportTicketDto) {
    return this.supportService.assignAdmin(ticketId, dto);
  }
}
