import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
  Request,
} from '@nestjs/common';
import { OrganizationsService } from './organizations.service';
import { CreateOrganizationDto, UpdateOrganizationDto } from './dto/organization.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { OperationLogsService } from '../operation-logs/operation-logs.service';
import { extractRequestInfo } from '../common/request-utils';
import { RequirePermission } from '../auth/decorators/permission.decorator';

@UseGuards(JwtAuthGuard)
@Controller('organizations')
export class OrganizationsController {
  constructor(
    private service: OrganizationsService,
    private logService: OperationLogsService,
  ) {}

  @Get()
  @RequirePermission('organization:view')
  findAll(
    @Query('includeArchived') includeArchived?: string,
    @Query('scope') scope?: 'all' | 'host' | 'external',
  ) {
    return this.service.findAll({ includeArchived: includeArchived === 'true', scope });
  }

  @Get(':id')
  @RequirePermission('organization:view')
  findOne(@Param('id') id: string) {
    return this.service.findOne(+id);
  }

  @Post()
  @RequirePermission('organization:create')
  async create(@Body() dto: CreateOrganizationDto, @Request() req: any) {
    const { ipAddress, userAgent } = extractRequestInfo(req);
    const result = await this.service.create(dto);
    await this.logService.log({
      userId: req.user?.id,
      username: req.user?.username,
      module: '机构管理',
      action: '新增机构',
      targetId: result.id,
      targetType: 'organization',
      detail: dto.name,
      ipAddress,
      userAgent,
    });
    return result;
  }

  @Put(':id')
  @RequirePermission('organization:edit')
  async update(@Param('id') id: string, @Body() dto: UpdateOrganizationDto, @Request() req: any) {
    const { ipAddress, userAgent } = extractRequestInfo(req);
    const result = await this.service.update(+id, dto);
    await this.logService.log({
      userId: req.user?.id,
      username: req.user?.username,
      module: '机构管理',
      action: '编辑机构',
      targetId: +id,
      targetType: 'organization',
      detail: JSON.stringify(dto),
      ipAddress,
      userAgent,
    });
    return result;
  }

  @Delete(':id')
  @RequirePermission('organization:delete')
  async remove(@Param('id') id: string, @Request() req: any) {
    const { ipAddress, userAgent } = extractRequestInfo(req);
    const result = await this.service.remove(+id);
    await this.logService.log({
      userId: req.user?.id,
      username: req.user?.username,
      module: '机构管理',
      action: '归档机构',
      targetId: +id,
      targetType: 'organization',
      ipAddress,
      userAgent,
    });
    return result;
  }
}
