import { Body, Controller, Delete, Get, Param, Patch, Post, Req, UploadedFile, UseGuards, UseInterceptors } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { memoryStorage } from 'multer';
import { Roles } from '../common/decorators/roles.decorator';
import { JwtAuthGuard } from '../common/guards/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { StorageService } from '../storage/storage.service';
import { SupportService } from './support.service';
import { UpsertSupportTicketDto } from './dto/upsert-support-ticket.dto';

@Controller('support-tickets')
@UseGuards(JwtAuthGuard, RolesGuard)
export class SupportController {
  constructor(
    private readonly supportService: SupportService,
    private readonly storageService: StorageService,
  ) {}

  @Get()
  @Roles('RESTAURANT', 'DRIVER', 'CUSTOMER', 'ADMIN', 'SUPER_ADMIN')
  index(@Req() req: { user: { sub: string; role: string } }) {
    return this.supportService.list(req.user as never);
  }

  @Post()
  @Roles('RESTAURANT', 'DRIVER', 'CUSTOMER', 'ADMIN', 'SUPER_ADMIN')
  create(@Req() req: { user: { sub: string; role: string } }, @Body() body: UpsertSupportTicketDto) {
    return this.supportService.create(req.user as never, body);
  }

  @Patch(':id')
  @Roles('RESTAURANT', 'DRIVER', 'CUSTOMER', 'ADMIN', 'SUPER_ADMIN')
  update(@Req() req: { user: { sub: string; role: string } }, @Param('id') id: string, @Body() body: Partial<UpsertSupportTicketDto>) {
    return this.supportService.update(req.user as never, id, body);
  }

  @Post(':id/attachments')
  @Roles('RESTAURANT', 'DRIVER', 'CUSTOMER', 'ADMIN', 'SUPER_ADMIN')
  @UseInterceptors(FileInterceptor('file', { storage: memoryStorage() }))
  async addAttachment(
    @Req() req: { user: { sub: string; role: string } },
    @Param('id') id: string,
    @UploadedFile() file: Express.Multer.File | undefined,
  ) {
    const stored = await this.storageService.savePublicFile(file, 'support');
    return this.supportService.addAttachment(req.user as never, id, stored.url);
  }

  @Delete(':id')
  @Roles('RESTAURANT', 'DRIVER', 'CUSTOMER', 'ADMIN', 'SUPER_ADMIN')
  archive(@Req() req: { user: { sub: string; role: string } }, @Param('id') id: string) {
    return this.supportService.archive(req.user as never, id);
  }
}
