import { Body, Controller, Delete, Get, Param, Patch, Post, Query, UseGuards } from '@nestjs/common';
import { UserRole } from '@prisma/client';
import { JwtAuthGuard } from '../../common/auth/jwt-auth.guard';
import { RequireTenantGuard } from '../../common/auth/require-tenant.guard';
import { RolesGuard } from '../../common/auth/roles.guard';
import { Roles } from '../../common/auth/roles.decorator';
import { CurrentTenant } from '../../common/auth/current-tenant.decorator';
import { RequestTenantContext } from '../../common/tenancy/tenant-query.helper';
import { ServicesService } from './services.service';
import { CreateServiceDto } from './dto/create-service.dto';
import { UpdateServiceDto } from './dto/update-service.dto';
import { ListServicesQuery } from './dto/list-services.query';

@Controller('services')
@UseGuards(JwtAuthGuard, RequireTenantGuard, RolesGuard)
export class ServicesController {
  constructor(private readonly services: ServicesService) {}

  // Returns the organization's services, optionally active only or filtered by search. GET /api/services
  @Get()
  list(@CurrentTenant() t: RequestTenantContext, @Query() query: ListServicesQuery) {
    return this.services.list(t, query);
  }

  // Creates a service (Org Admin only). POST /api/services
  @Post()
  @Roles(UserRole.ORGANIZATION_ADMIN)
  create(@CurrentTenant() t: RequestTenantContext, @Body() dto: CreateServiceDto) {
    return this.services.create(t, dto);
  }

  // Updates a service and renames it on linked leads (Org Admin only). PATCH /api/services/:id
  @Patch(':id')
  @Roles(UserRole.ORGANIZATION_ADMIN)
  update(@CurrentTenant() t: RequestTenantContext, @Param('id') id: string, @Body() dto: UpdateServiceDto) {
    return this.services.update(t, id, dto);
  }

  // Switches a service between active and inactive (Org Admin only). PATCH /api/services/:id/toggle
  @Patch(':id/toggle')
  @Roles(UserRole.ORGANIZATION_ADMIN)
  toggleActive(@CurrentTenant() t: RequestTenantContext, @Param('id') id: string) {
    return this.services.toggleActive(t, id);
  }

  // Deletes a service that no lead uses (Org Admin only). DELETE /api/services/:id
  @Delete(':id')
  @Roles(UserRole.ORGANIZATION_ADMIN)
  remove(@CurrentTenant() t: RequestTenantContext, @Param('id') id: string) {
    return this.services.remove(t, id);
  }
}
