import { Controller, Get, Post, Put, Delete, Body, Param, UseGuards, Request } from '@nestjs/common';
import { ExpenseTypesService } from './expense-types.service';
import { CreateExpenseTypeDto, UpdateExpenseTypeDto } from './dto/expense-type.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('expense-types')
export class ExpenseTypesController {
  constructor(
    private readonly service: ExpenseTypesService,
    private readonly logService: OperationLogsService,
  ) {}

  @Get()
  @RequirePermission('expense:view')
  findAll() {
    return this.service.findAll();
  }

  @Get('admin')
  @RequirePermission('expense:edit')
  findAllAdmin() {
    return this.service.findAllAdmin();
  }

  @Post()
  @RequirePermission('expense:create')
  async create(@Body() dto: CreateExpenseTypeDto, @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: 'expense_type',
      detail: `${dto.code} - ${dto.name}`,
      ipAddress,
      userAgent,
    });
    return result;
  }

  @Put(':id')
  @RequirePermission('expense:edit')
  async update(@Param('id') id: string, @Body() dto: UpdateExpenseTypeDto, @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: 'expense_type',
      detail: JSON.stringify(dto),
      ipAddress,
      userAgent,
    });
    return result;
  }

  @Delete(':id')
  @RequirePermission('expense:delete')
  async remove(@Param('id') id: string, @Request() req: any) {
    const { ipAddress, userAgent } = extractRequestInfo(req);
    await this.service.remove(+id);
    await this.logService.log({
      userId: req.user?.id,
      username: req.user?.username,
      module: '费用类型',
      action: '停用费用类型',
      targetId: +id,
      targetType: 'expense_type',
      ipAddress,
      userAgent,
    });
    return { message: '已停用' };
  }
}
