import {
  Controller,
  Delete,
  Get,
  Headers,
  HttpCode,
  Param,
  ParseIntPipe,
  Post,
  Query,
  Req,
  UseGuards,
} from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { Roles } from '@/casl/roles.decorator';
import { RolesGuard } from '@/casl/roles.guard';
import { JwtAuthGuard } from '@/modules/auth/jwt-auth.guard';
import { RecycleBinQuery } from './recycle-bin.dto';
import { RecycleBinService } from './recycle-bin.service';

@ApiTags('Recycle Bin')
@ApiBearerAuth('access-token')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('admin', 'Administrator')
@Controller('admin/recycle-bin')
export class RecycleBinController {
  constructor(private readonly records: RecycleBinService) {}

  @Get()
  list(@Query() query: RecycleBinQuery) {
    return this.records.list(query);
  }

  @Get(':type/:id')
  detail(@Param('type') type: string, @Param('id', ParseIntPipe) id: number) {
    return this.records.detail(this.records.parseType(type), id);
  }

  @Post(':type/:id/restore')
  @HttpCode(200)
  restore(
    @Param('type') type: string,
    @Param('id', ParseIntPipe) id: number,
    @Req() request: { user: { id: number } },
    @Headers('accept-language') language?: string,
  ) {
    return this.records.restore(
      this.records.parseType(type),
      id,
      request.user.id,
      language,
    );
  }

  @Delete(':type/:id')
  @HttpCode(200)
  @ApiOperation({
    summary: 'Permanently delete a record from Recycle Bin',
    description:
      'Permanently removes the selected soft-deleted record, its owned details and association rows. Clears known optional links while preserving shared main records. Required references must be reassigned first; otherwise the whole transaction is rejected. Uploaded files and historical activity logs are preserved. Only administrators can delete records.',
  })
  permanentlyDelete(
    @Param('type') type: string,
    @Param('id', ParseIntPipe) id: number,
    @Req() request: { user: { id: number } },
    @Headers('accept-language') language?: string,
  ) {
    return this.records.permanentlyDelete(
      this.records.parseType(type),
      id,
      request.user.id,
      language,
    );
  }
}
