import {
  Controller,
  Post,
  Get,
  Body,
  Req,
  UseGuards,
} from '@nestjs/common';
import { Request } from 'express';
import { ClsService } from 'nestjs-cls';
import { AuthService } from './auth.service';
import { LoginDto } from './dto';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import { CLS_TENANT_ID } from '../common/cls/cls.constants';
import { successResponse } from '../common/responses/api-response';

/**
 * AuthController — login and profile endpoints.
 *
 * POST /api/auth/login  — public (tenant middleware still runs, CLS has tenant_id)
 * GET  /api/auth/profile — protected (JWT required)
 */
@Controller('auth')
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly cls: ClsService,
  ) {}

  @Post('login')
  async login(@Body() dto: LoginDto) {
    const tenantId = this.cls.get<string>(CLS_TENANT_ID);
    const data = await this.authService.login(dto, tenantId);
    return successResponse(data, 'Login successful');
  }

  @UseGuards(JwtAuthGuard)
  @Get('profile')
  async getProfile(@Req() req: Request) {
    const user = (req as any).user;
    const tenantId = this.cls.get<string>(CLS_TENANT_ID);
    const data = await this.authService.getProfile(user.id, tenantId);
    return successResponse(data, 'Profile fetched successfully');
  }
}
