import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { Role } from '@prisma/client';

@Injectable()
export class AuthService {
  private readonly logger = new Logger(AuthService.name);

  constructor(private prisma: PrismaService) {}

  /**
   * Validate and get/create user from Auth0 token payload
   */
  async validateUser(payload: any) {
    const namespace = 'https://vip-coordinator-api';
    const auth0Id = payload.sub;
    const email = payload[`${namespace}/email`] || payload.email || `${auth0Id}@auth0.local`;
    const name = payload[`${namespace}/name`] || payload.name || 'Unknown User';
    const picture = payload[`${namespace}/picture`] || payload.picture;

    // Check if user exists
    let user = await this.prisma.user.findUnique({
      where: { auth0Id },
      include: { driver: true },
    });

    if (!user) {
      // Check if this is the first user (auto-approve as admin)
      const approvedUserCount = await this.prisma.user.count({
        where: { isApproved: true, deletedAt: null },
      });
      const isFirstUser = approvedUserCount === 0;

      this.logger.log(
        `Creating new user: ${email} (approvedUserCount: ${approvedUserCount}, isFirstUser: ${isFirstUser})`,
      );

      // Create new user
      // First user is auto-approved as ADMINISTRATOR
      // Subsequent users default to DRIVER and require approval
      user = await this.prisma.user.create({
        data: {
          auth0Id,
          email,
          name,
          picture,
          role: isFirstUser ? Role.ADMINISTRATOR : Role.DRIVER,
          isApproved: isFirstUser, // Auto-approve first user only
        },
        include: { driver: true },
      });

      this.logger.log(
        `User created: ${user.email} with role ${user.role} (approved: ${user.isApproved})`,
      );
    }

    return user;
  }

  /**
   * Get current user profile
   */
  async getCurrentUser(auth0Id: string) {
    return this.prisma.user.findUnique({
      where: { auth0Id },
      include: { driver: true },
    });
  }
}
