import { Body, Controller, Get, Param, Patch, Post, Query, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { AuthenticatedUser } from '../auth/auth.types';
import { AuthGuard } from '../common/auth.guard';
import { PermissionGuard } from '../common/permission.guard';
import { RequirePermission } from '../common/permission.decorator';
import { CreateTemplateDto } from './dto/create-template.dto';
import { UpdateTemplateDto } from './dto/update-template.dto';
import { TemplatesService } from './templates.service';

@UseGuards(AuthGuard, PermissionGuard)
@Controller('templates')
export class TemplatesController {
  constructor(private readonly templatesService: TemplatesService) {}

  @Get()
  @RequirePermission('templates', 'view')
  findAll(
    @Query('search') search?: string,
    @Query('category') category?: string,
    @Query('status') status?: string,
    @Query('language') language?: string,
  ) {
    return this.templatesService.findAll({ search, category, status, language });
  }

  @Get(':id')
  @RequirePermission('templates', 'view')
  findOne(@Param('id') id: string) {
    return this.templatesService.findOne(id);
  }

  @Post()
  @RequirePermission('templates', 'edit')
  create(
    @Req() request: Request & { user: AuthenticatedUser },
    @Body() dto: CreateTemplateDto,
  ) {
    return this.templatesService.create(dto, request.user, request.ip);
  }

  @Patch(':id')
  @RequirePermission('templates', 'edit')
  update(
    @Req() request: Request & { user: AuthenticatedUser },
    @Param('id') id: string,
    @Body() dto: UpdateTemplateDto,
  ) {
    return this.templatesService.update(id, dto, request.user, request.ip);
  }
}
