import {
  Controller,
  Post,
  Body,
  Headers,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { IsString, IsNotEmpty, IsOptional } from 'class-validator';
import { AuthService } from './auth.service';

class CreateAnonymousDto {
  @IsOptional()
  @IsString()
  fingerprint?: string;
}

class SendCodeDto {
  @IsNotEmpty()
  @IsString()
  phone: string;
}

class VerifyCodeDto {
  @IsNotEmpty()
  @IsString()
  phone: string;

  @IsNotEmpty()
  @IsString()
  code: string;
}

class RefreshTokenDto {
  @IsNotEmpty()
  @IsString()
  token: string;
}

@Controller('auth')
export class AuthController {
  constructor(private authService: AuthService) {}

  /**
   * Create anonymous session
   * POST /api/v1/auth/anonymous
   */
  @Post('anonymous')
  @HttpCode(HttpStatus.OK)
  async createAnonymousSession(@Body() dto: CreateAnonymousDto) {
    const result = await this.authService.createAnonymousSession(dto.fingerprint || '');
    return {
      success: true,
      data: result,
    };
  }

  /**
   * Send verification code
   * POST /api/v1/auth/send-code
   */
  @Post('send-code')
  @HttpCode(HttpStatus.OK)
  async sendVerificationCode(@Body() dto: SendCodeDto) {
    const result = await this.authService.sendVerificationCode(dto.phone);
    return {
      success: true,
      data: result,
    };
  }

  /**
   * Verify code and login
   * POST /api/v1/auth/verify-phone
   */
  @Post('verify-phone')
  @HttpCode(HttpStatus.OK)
  async verifyPhone(
    @Body() dto: VerifyCodeDto,
    @Headers('x-user-id') userId?: string,
  ) {
    const result = await this.authService.verifyAndLogin(
      dto.phone,
      dto.code,
      userId,
    );
    return {
      success: true,
      data: result,
    };
  }

  /**
   * Refresh token
   * POST /api/v1/auth/refresh
   */
  @Post('refresh')
  @HttpCode(HttpStatus.OK)
  async refreshToken(@Body() dto: RefreshTokenDto) {
    const result = await this.authService.refreshToken(dto.token);
    return {
      success: true,
      data: result,
    };
  }

  /**
   * Logout (client-side action, just acknowledge)
   * POST /api/v1/auth/logout
   */
  @Post('logout')
  @HttpCode(HttpStatus.OK)
  async logout() {
    return {
      success: true,
      message: 'Logged out successfully',
    };
  }
}
