import {
  Body,
  Controller,
  Delete,
  Get,
  HttpStatus,
  Ip,
  Param,
  Patch,
  Post,
  Req,
  Res,
  UseGuards,
  UsePipes,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
import { ZodValidationPipe } from '../../common/pipes/zod-validation.pipe';
import { JwtAuthGuard } from '../owner/guards/jwt.guard';
import {
  CreateIpWhitelistDto,
  UpdateIpWhitelistDto,
  createIpWhitelistSchema,
  updateIpWhitelistSchema,
} from './ip-whitelist.dto';
import { IpWhitelistService } from './ip-whitelist.service';

@Controller('ip-whitelist')
@UseGuards(JwtAuthGuard)
export class IpWhitelistController {
  constructor(private readonly service: IpWhitelistService) {}

  @Get('detect-ip')
  async detectClientIp(
    @Req() req: Request,
    @Ip() ip: string,
    @Res() res: Response,
  ) {
    const forwarded = req.headers['x-forwarded-for'];
    let clientIp = req.ip || ip || '127.0.0.1';
    if (typeof forwarded === 'string') {
      clientIp = forwarded.split(',')[0].trim();
    } else if (Array.isArray(forwarded) && forwarded.length > 0) {
      clientIp = forwarded[0].trim();
    }
    const normalized = this.service.normalizeIp(clientIp);

    return res.status(HttpStatus.OK).json({
      status: HttpStatus.OK,
      message: 'Client IP detected successfully',
      data: {
        client_ip: normalized,
        raw_ip: clientIp,
        is_local:
          normalized === '127.0.0.1' ||
          normalized === 'localhost' ||
          normalized.startsWith('192.168.') ||
          normalized.startsWith('10.') ||
          normalized.startsWith('172.16.'),
      },
    });
  }

  @Get()
  async getAll(@CurrentUser() owner_id: string, @Res() res: Response) {
    const result = await this.service.getAll(owner_id);
    return res.status(HttpStatus.OK).json(result);
  }

  @Post()
  @UsePipes(new ZodValidationPipe(createIpWhitelistSchema))
  async create(
    @Body() body: CreateIpWhitelistDto,
    @CurrentUser() owner_id: string,
    @Res() res: Response,
  ) {
    const result = await this.service.create(body, owner_id);
    return res.status(HttpStatus.CREATED).json(result);
  }

  @Patch(':id')
  @UsePipes(new ZodValidationPipe(updateIpWhitelistSchema))
  async update(
    @Param('id') id: string,
    @Body() body: UpdateIpWhitelistDto,
    @CurrentUser() owner_id: string,
    @Res() res: Response,
  ) {
    const result = await this.service.update(id, body, owner_id);
    return res.status(HttpStatus.OK).json(result);
  }

  @Delete(':id')
  async delete(
    @Param('id') id: string,
    @CurrentUser() owner_id: string,
    @Res() res: Response,
  ) {
    const result = await this.service.delete(id, owner_id);
    return res.status(HttpStatus.OK).json(result);
  }
}
