import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
  ParseUUIDPipe,
} from '@nestjs/common';
import { SupplierService } from './supplier.service';
import { CreateSupplierDto, UpdateSupplierDto } from './dto';
import { IsOptional, IsString, IsUUID, IsArray, MaxLength } from 'class-validator';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { PermissionGuard } from '../../auth/guards/permission.guard';
import { Permissions } from '../../auth/decorators/permissions.decorator';
import { AccessLevel, ModuleName } from '../../entities/role-permission.entity';
import { paginatedResponse, successResponse } from '../../common/responses/api-response';
import { PaginationDto } from '../../common/dto/pagination.dto';
import { Lookup } from '../../common/decorators/lookup.decorator';

/**
 * Inline DTO for the Planner's free-text quick-create. Kept here
 * (not in dto/) so it's obvious this isn't the full-feature create
 * form — just the 3 minimum fields Planner typing path needs.
 */
class QuickCreateSupplierDto {
  @IsString()
  @MaxLength(255)
  name: string;

  @IsUUID()
  destination_id: string;

  @IsArray()
  @IsOptional()
  @IsString({ each: true })
  supplier_types?: string[];
}

@Controller('suppliers')
@UseGuards(JwtAuthGuard, PermissionGuard)
export class SupplierController {
  constructor(private readonly service: SupplierService) {}

  /**
   * Planner typing path — creates a minimal supplier when ops types
   * a free-text name that doesn't match any existing master row.
   *
   * Per stakeholder spec (Sales cannot create suppliers inline), the
   * endpoint is gated by the `supplier:create` permission. Sales and
   * other VIEW-only roles hit a 403 here; their typed-in names save
   * as `supplier_name_text` on the booking row instead. The frontend
   * Planner skips calling this endpoint entirely for those roles —
   * the server check is the defence-in-depth backstop.
   */
  @Post('quick-create')
  @Permissions({ module: ModuleName.SUPPLIER, accessLevel: AccessLevel.CREATE })
  async quickCreate(@Body() dto: QuickCreateSupplierDto) {
    const result = await this.service.findOrCreateByName({
      name: dto.name,
      destination_id: dto.destination_id,
      supplier_types: dto.supplier_types,
    });
    return successResponse(
      result,
      result.created ? 'Supplier created' : 'Existing supplier matched',
    );
  }

  @Get()
  @Permissions({ module: ModuleName.SUPPLIER, accessLevel: AccessLevel.VIEW })
  async findAll(
    @Query() query: PaginationDto,
    @Query('destination_id') destinationId?: string,
    @Query('supplier_type') supplierType?: string,
  ) {
    const { items, meta } = await this.service.findAll(query, { destinationId, supplierType });
    return paginatedResponse(items, meta, 'Suppliers fetched successfully');
  }

  @Get('lookup')
  @Lookup()
  async lookup() {
    const items = await this.service.findAllForLookup();
    return successResponse(items, 'Suppliers lookup');
  }

  @Get(':id')
  @Permissions({ module: ModuleName.SUPPLIER, accessLevel: AccessLevel.VIEW })
  async findById(@Param('id', ParseUUIDPipe) id: string) {
    const data = await this.service.findById(id);
    return successResponse(data, 'Supplier fetched successfully');
  }

  @Post()
  @Permissions({ module: ModuleName.SUPPLIER, accessLevel: AccessLevel.CREATE })
  async create(@Body() dto: CreateSupplierDto) {
    const result = await this.service.create(dto);
    return successResponse(result, result.message);
  }

  @Patch(':id')
  @Permissions({ module: ModuleName.SUPPLIER, accessLevel: AccessLevel.EDIT })
  async update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateSupplierDto) {
    const result = await this.service.update(id, dto);
    return successResponse(result, result.message);
  }

  @Delete(':id')
  @Permissions({ module: ModuleName.SUPPLIER, accessLevel: AccessLevel.DELETE })
  async remove(@Param('id', ParseUUIDPipe) id: string) {
    const result = await this.service.remove(id);
    return successResponse(result, result.message);
  }
}
