import { Controller, Get } from '@nestjs/common';
import { ClsService } from 'nestjs-cls';
import type { UserProfile } from '@sar/api-interface';
import type { WorkspaceClsStore } from '../workspace/workspace.types';
import type { PrismaClient } from '@prisma/client';

@Controller({ path: 'auth' })
export class AuthController {
  constructor(private readonly cls: ClsService<WorkspaceClsStore>) {}

  @Get('me')
  async me(): Promise<UserProfile> {
    const prisma = this.cls.get('prisma') as PrismaClient;
    const userId = this.cls.get('userId') ?? '';
    const role = this.cls.get('role') ?? 'rep';
    const idEmpresa = this.cls.get('idEmpresa');

    // Representante é cadastro global (sem id_empresa).
    const rows = await prisma.$queryRaw<{ codigo: number; nome: string }[]>`
      SELECT codigo, nome
      FROM sar.vw_representantes
      WHERE codigo = ${parseInt(userId, 10)}
      LIMIT 1
    `;

    const row = rows[0];
    return {
      codVendedor: row?.codigo ?? parseInt(userId, 10),
      nome: row?.nome ?? userId,
      role,
      idEmpresa,
    };
  }
}
