import { logger } from '@/lib/logger';
import { checkDashboardAccess } from '@/lib/dashboard-access';
import { convexQuery } from '@/lib/convex-client';

export interface DashboardInitialData {
  user: {
    id: string;
    email?: string;
    name?: string;
  };
  accessStatus: {
    hasAccess: boolean;
    redirectUrl?: string;
    reason?: string;
  };
  integrationConfig: {
    hasWhatsApp: boolean;
    hasVoiceAgent: boolean;
    voiceAgentConfig: null; // Placeholder for future
  };
}

interface ConvexUser {
  _id: string;
  prismaId?: string;
  appUserId?: string;
  email?: string;
  name?: string;
  n8nWebhookUrl?: string;
  n8nWorkflowId?: string;
  voiceAgentId?: string;
}

interface ConvexOrganizationState {
  organization?: Record<string, unknown>;
}

export class DashboardService {
  /**
   * Fetches all initial data required to render the dashboard server-side.
   * Encapsulates access control checks and Convex data fetching.
   *
   * All data access goes through Convex. No Prisma fallback.
   */
  static async getInitialData(userId: string, sessionUser?: { email?: string; name?: string }): Promise<DashboardInitialData> {
    const scopedLogger = logger.scope('DashboardService');

    // 1. Check Access Permissions
    const accessStatus = await checkDashboardAccess(userId, sessionUser?.email);
    if (!accessStatus.hasAccess) {
      scopedLogger.info('Dashboard access denied', { userId, redirectUrl: accessStatus.redirectUrl });
      return {
        user: { id: userId, email: sessionUser?.email, name: sessionUser?.name },
        accessStatus,
        integrationConfig: { hasWhatsApp: false, hasVoiceAgent: false, voiceAgentConfig: null },
      };
    }

    // 2. Fetch user profile + org state from Convex in parallel.
    //    WhatsApp credentials live on the organization row (Twilio) or on the
    //    user row (legacy n8n), so we need both to compute `hasWhatsApp`.
    try {
      const [convexUser, orgState] = await Promise.all([
        sessionUser?.email
          ? convexQuery<ConvexUser>("auth/queries:getUserByEmail", { email: sessionUser.email })
          : Promise.resolve(null),
        convexQuery<ConvexOrganizationState>(
          "organizations/queries:getOrganizationStateByUserId",
          { userId },
        ).catch(() => null),
      ]);

      const userName = convexUser?.name || sessionUser?.name;

      // Legacy n8n-driven WhatsApp (older orgs configured via n8n workflow)
      const hasLegacyN8n =
        !!convexUser?.n8nWebhookUrl || !!convexUser?.n8nWorkflowId;

      // Twilio-driven WhatsApp (current path) — credentials are on the org row
      const orgRow = orgState?.organization as
        | Record<string, unknown>
        | undefined;
      const hasTwilioWhatsApp = !!(
        orgRow?.twilioAccountSid && orgRow?.twilioWhatsappNumber
      );

      // Meta Cloud API path — org.whatsappPhoneNumberId is the WA Business phone ID
      const hasMetaWhatsApp = !!orgRow?.whatsappPhoneNumberId;

      const hasWhatsApp = hasLegacyN8n || hasTwilioWhatsApp || hasMetaWhatsApp;
      const hasVoiceAgent = !!convexUser?.voiceAgentId;

      scopedLogger.info('Dashboard initial data fetched via Convex', {
        userId,
        hasWhatsApp,
        hasVoiceAgent,
      });
      return {
        user: { id: userId, email: sessionUser?.email, name: userName },
        accessStatus,
        integrationConfig: { hasWhatsApp, hasVoiceAgent, voiceAgentConfig: null },
      };
    } catch (error) {
      scopedLogger.error('Convex user fetch failed', { userId, error });

      // Return with defaults if Convex fails
      return {
        user: { id: userId, email: sessionUser?.email, name: sessionUser?.name },
        accessStatus,
        integrationConfig: { hasWhatsApp: false, hasVoiceAgent: false, voiceAgentConfig: null },
      };
    }
  }
}
