import {
  Body,
  Controller,
  Delete,
  Get,
  HttpCode,
  Param,
  Patch,
  Post,
  Req,
  UseGuards,
} from '@nestjs/common'
import { clientIp } from '../auth/client-ip.js'
import { CurrentUser } from '../auth/current-user.decorator.js'
import { JwtAuthGuard } from '../auth/jwt-auth.guard.js'
import { OperatorGuard } from '../auth/operator.guard.js'
import type { AuthentikJwtPayload } from '../auth/jwt-payload.interface.js'
import { CreateFlagDto } from './dto/create-flag.dto.js'
import { EvaluateDto } from './dto/evaluate.dto.js'
import { UpdateFlagDto } from './dto/update-flag.dto.js'
import { FlagsService } from './flags.service.js'

// Read access is open to any authed token (eval works for any tenant member);
// mutations require an operator-scoped token + platformAdmin. Same shape as
// PartnersController so the auth model stays predictable.
@Controller('flags')
@UseGuards(JwtAuthGuard)
export class FlagsController {
  constructor(private readonly flags: FlagsService) {}

  @Get()
  findAll() {
    return this.flags.findAll()
  }

  @Get(':key')
  findOne(@Param('key') key: string) {
    return this.flags.findOne(key)
  }

  @Post('evaluate')
  evaluate(@Body() dto: EvaluateDto) {
    return this.flags.evaluateAll(dto.tenantSlug)
  }

  @Post()
  @UseGuards(OperatorGuard)
  create(
    @Body() dto: CreateFlagDto,
    @CurrentUser() jwt: AuthentikJwtPayload,
    @Req() req: Parameters<typeof clientIp>[0],
  ) {
    return this.flags.create(dto, { email: jwt.email, ip: clientIp(req) })
  }

  @Patch(':key')
  @UseGuards(OperatorGuard)
  update(
    @Param('key') key: string,
    @Body() dto: UpdateFlagDto,
    @CurrentUser() jwt: AuthentikJwtPayload,
    @Req() req: Parameters<typeof clientIp>[0],
  ) {
    return this.flags.update(key, dto, { email: jwt.email, ip: clientIp(req) })
  }

  @Delete(':key')
  @HttpCode(204)
  @UseGuards(OperatorGuard)
  async remove(
    @Param('key') key: string,
    @CurrentUser() jwt: AuthentikJwtPayload,
    @Req() req: Parameters<typeof clientIp>[0],
  ) {
    await this.flags.remove(key, { email: jwt.email, ip: clientIp(req) })
  }
}
