// server/src/model-config/model-config.controller.ts
import {
  Body,
  Controller,
  Delete,
  Get,
  HttpCode,
  HttpStatus,
  Param,
  Patch,
  Post,
  Put,
  Req,
  UseGuards,
} from '@nestjs/common';
import { ModelConfigService } from './model-config.service';
import { CreateModelConfigDto } from './dto/create-model-config.dto';
import { UpdateModelConfigDto } from './dto/update-model-config.dto';
import { CombinedAuthGuard } from '../auth/combined-auth.guard';
import { RolesGuard } from '../auth/roles.guard';
import { Roles } from '../auth/roles.decorator';
import { UserRole } from '../user/user-role.enum';
import { ModelConfigResponseDto } from './dto/model-config-response.dto';
import { plainToClass } from 'class-transformer';

@UseGuards(CombinedAuthGuard)
@Controller('models') // Global prefix /api/models
export class ModelConfigController {
  constructor(private readonly modelConfigService: ModelConfigService) {}

  @Roles(UserRole.TENANT_ADMIN, UserRole.SUPER_ADMIN)
  @Post()
  @HttpCode(HttpStatus.CREATED)
  async create(
    @Body() createModelConfigDto: CreateModelConfigDto,
  ): Promise<ModelConfigResponseDto> {
    const modelConfig =
      await this.modelConfigService.create(createModelConfigDto);
    return plainToClass(ModelConfigResponseDto, modelConfig);
  }

  @Get()
  async findAll(): Promise<ModelConfigResponseDto[]> {
    const modelConfigs = await this.modelConfigService.findAll();
    return modelConfigs.map((mc) => plainToClass(ModelConfigResponseDto, mc));
  }

  @Get(':id')
  async findOne(@Param('id') id: string): Promise<ModelConfigResponseDto> {
    const modelConfig = await this.modelConfigService.findOne(id);
    return plainToClass(ModelConfigResponseDto, modelConfig);
  }

  @Roles(UserRole.TENANT_ADMIN, UserRole.SUPER_ADMIN)
  @Put(':id')
  async update(
    @Param('id') id: string,
    @Body() updateModelConfigDto: UpdateModelConfigDto,
  ): Promise<ModelConfigResponseDto> {
    const modelConfig = await this.modelConfigService.update(
      id,
      updateModelConfigDto,
    );
    return plainToClass(ModelConfigResponseDto, modelConfig);
  }

  @Roles(UserRole.TENANT_ADMIN, UserRole.SUPER_ADMIN)
  @Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)
  async remove(@Param('id') id: string): Promise<void> {
    await this.modelConfigService.remove(id);
  }

  @Roles(UserRole.TENANT_ADMIN, UserRole.SUPER_ADMIN)
  @Patch(':id/set-default')
  async setDefault(@Param('id') id: string): Promise<ModelConfigResponseDto> {
    const modelConfig = await this.modelConfigService.setDefault(id);
    return plainToClass(ModelConfigResponseDto, modelConfig);
  }
}
