import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  Req,
  UseGuards,
} from '@nestjs/common';
import { OrgService } from './org.service';
import { AuthGuard } from '../auth/auth.guard';
import { FeatureFlagGuard } from '../feature-flags/feature-flag.guard';
import { RequireFeature } from '../feature-flags/require-feature.decorator';
import {
  RegisterPartnerDto,
  UpdateOrganisationDto,
  AddAnimalDto,
  UpdateAnimalDto,
} from './org.dto';

@Controller('org')
export class OrgController {
  constructor(private readonly orgService: OrgService) {}

  // ── Public routes ──
  @Get('public')
  @UseGuards(FeatureFlagGuard)
  @RequireFeature('feature_vets_enabled')
  getPublicOrganisations(@Query() query: any) {
    return this.orgService.getPublicOrganisations(query);
  }

  // ── Protected routes (declared before `/:id` so `/me` is not captured as an id) ──
  @Post('register')
  @UseGuards(AuthGuard)
  registerPartner(@Req() req: any, @Body() body: RegisterPartnerDto) {
    return this.orgService.registerPartner(req.user.id, body);
  }

  @Get('me')
  @UseGuards(AuthGuard)
  getMyOrganisation(@Req() req: any) {
    return this.orgService.getMyOrganisation(req.user.id);
  }

  @Put('me')
  @UseGuards(AuthGuard)
  updateMyOrganisation(@Req() req: any, @Body() body: UpdateOrganisationDto) {
    return this.orgService.updateMyOrganisation(req.user.id, body);
  }

  @Get('me/animals')
  @UseGuards(AuthGuard)
  getMyAnimals(@Req() req: any) {
    return this.orgService.getMyAnimals(req.user.id);
  }

  @Post('me/animals')
  @UseGuards(AuthGuard)
  addAnimal(@Req() req: any, @Body() body: AddAnimalDto) {
    return this.orgService.addAnimal(req.user.id, body);
  }

  @Get('me/animals/:animalId')
  @UseGuards(AuthGuard)
  getMyAnimal(@Req() req: any, @Param('animalId') animalId: string) {
    return this.orgService.getMyAnimal(req.user.id, animalId);
  }

  @Put('me/animals/:animalId')
  @UseGuards(AuthGuard)
  updateMyAnimal(
    @Req() req: any,
    @Param('animalId') animalId: string,
    @Body() body: UpdateAnimalDto,
  ) {
    return this.orgService.updateMyAnimal(req.user.id, animalId, body);
  }

  @Delete('me/animals/:animalId')
  @UseGuards(AuthGuard)
  deleteMyAnimal(@Req() req: any, @Param('animalId') animalId: string) {
    return this.orgService.deleteMyAnimal(req.user.id, animalId);
  }

  // ── Public param routes (declared last so literals above win) ──
  @Get(':id')
  getOrganisation(@Param('id') id: string) {
    return this.orgService.getOrganisation(id);
  }

  @Get(':id/animals')
  getOrganisationAnimals(@Param('id') id: string) {
    return this.orgService.getOrganisationAnimals(id);
  }
}
