import { Controller, Get, Post, Put, Delete, Param, Body, UseGuards, ParseIntPipe, Query } from '@nestjs/common';
import { ReorderDto } from '../common/dto/reorder.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { Permissions } from '../auth/permissions.decorator';
import { PermissionsGuard } from '../auth/guards/permissions.guard';
import { SectionsService } from './sections.service';
import { CreateSectionDto } from './dto/create-section.dto';
import { UpdateSectionDto } from './dto/update-section.dto';

@Controller('api/v1/admin/sections')
@UseGuards(JwtAuthGuard, PermissionsGuard)
export class SectionsController {
  constructor(private readonly sectionsService: SectionsService) {}

  @Post()
  @Permissions('section.create')
  async create(@Body() dto: CreateSectionDto) {
    const section = await this.sectionsService.create(dto);
    return { success: true, data: section };
  }

  @Get()
  @Permissions('section.view')
  async findAll(@Query('status') status?: string) {
    const sections = await this.sectionsService.findAll(status);
    return { success: true, data: sections };
  }

  @Post('reorder')
  @Permissions('section.update')
  async reorder(@Body() dto: ReorderDto) {
    await this.sectionsService.reorder(dto.items);
    return { success: true, message: 'Sections reordered' };
  }

  @Get(':id')
  @Permissions('section.view')
  async findById(@Param('id', ParseIntPipe) id: number) {
    const section = await this.sectionsService.findById(id);
    if (!section) {
      return { success: false, message: 'Section not found' };
    }
    return { success: true, data: section };
  }

  @Put(':id')
  @Permissions('section.update')
  async update(
    @Param('id', ParseIntPipe) id: number,
    @Body() dto: UpdateSectionDto,
  ) {
    const section = await this.sectionsService.update(id, dto);
    if (!section) {
      return { success: false, message: 'Section not found' };
    }
    return { success: true, data: section };
  }

  @Delete(':id')
  @Permissions('section.delete')
  async delete(@Param('id', ParseIntPipe) id: number) {
    const success = await this.sectionsService.delete(id);
    return { success, message: success ? 'Section deleted' : 'Section not found' };
  }

  @Post(':id/publish')
  @Permissions('section.publish')
  async publish(@Param('id', ParseIntPipe) id: number) {
    const section = await this.sectionsService.publish(id);
    if (!section) {
      return { success: false, message: 'Section not found' };
    }
    return { success: true, data: section };
  }

  @Post(':id/archive')
  @Permissions('section.publish')
  async archive(@Param('id', ParseIntPipe) id: number) {
    const section = await this.sectionsService.archive(id);
    if (!section) {
      return { success: false, message: 'Section not found' };
    }
    return { success: true, data: section };
  }
}
