import {
  Controller,
  Get,
  Query,
  Post,
  Body,
  Put,
  Param,
  Patch,
  Delete,
} from '@nestjs/common';
import { StateService } from './state.service';
import { Public } from '../auth/public.decorator';
import {
  ApiBearerAuth,
  ApiTags,
  ApiBody,
  ApiParam,
  ApiQuery,
  ApiOperation,
} from '@nestjs/swagger';

@ApiTags('state')
@ApiBearerAuth('access-token')
@Controller('state')
export class StateController {
  constructor(private readonly stateService: StateService) {}
  @Public()
  @Get()
  @ApiOperation({ summary: 'Get all states' })
  findAll() {
    return this.stateService.findAll();
  }

  @Public()
  @Get('filtered')
  @ApiOperation({ summary: 'Find States by Country' })
  @ApiQuery({ name: 'status', required: false, type: Number })
  findByCountry(
    @Query('country_id') countryId: any,
    @Query('page') page: any = 1,
    @Query('limit') limit: any = 10,
    @Query('status') status?: any,
  ) {
    const cId = !isNaN(Number(countryId)) ? Number(countryId) : undefined;
    const p = !isNaN(Number(page)) ? Number(page) : 1;
    const l = !isNaN(Number(limit)) ? Number(limit) : 10;
    const s =
      status !== undefined && !isNaN(Number(status))
        ? Number(status)
        : undefined;

    if (cId === undefined) {
      return {
        success: false,
        message: 'Country ID is required and must be a number',
      };
    }

    return this.stateService.findByCountry(cId, p, l, s);
  }

  @Public()
  @Get(':id')
  @ApiOperation({ summary: 'Get state by ID' })
  @ApiParam({ name: 'id', type: String })
  findOne(@Param('id') id: string) {
    if (isNaN(Number(id))) {
      return { success: false, message: 'Invalid ID' };
    }
    return this.stateService.findOne(+id);
  }

  @Public()
  @Post()
  @ApiOperation({ summary: 'Create State' })
  @ApiBody({
    schema: {
      type: 'object',
      properties: { name: { type: 'string' }, country_id: { type: 'number' } },
    },
  })
  create(@Body() body: any) {
    return this.stateService.create(body);
  }

  @Public()
  @Put(':id')
  @ApiOperation({ summary: 'Update State' })
  @ApiParam({ name: 'id', type: String })
  @ApiBody({
    schema: {
      type: 'object',
      properties: { name: { type: 'string' }, country_id: { type: 'number' } },
    },
  })
  update(@Param('id') id: string, @Body() body: any) {
    return this.stateService.update(+id, body);
  }

  @Public()
  @Patch(':id')
  @ApiOperation({ summary: 'Patch State' })
  @ApiParam({ name: 'id', type: String })
  @ApiBody({
    schema: {
      type: 'object',
      properties: { name: { type: 'string' }, country_id: { type: 'number' } },
    },
  })
  patch(@Param('id') id: string, @Body() body: any) {
    return this.stateService.update(+id, body);
  }

  @Public()
  @Delete(':id')
  @ApiOperation({ summary: 'Delete state' })
  @ApiParam({ name: 'id', type: String })
  remove(@Param('id') id: string) {
    return this.stateService.remove(+id);
  }
}
