import { cookies } from 'next/headers';
import { createAdminClient } from '@/shared/db/supabase-client';
import { logAuditEvent } from '@/shared/admin/audit';

// --- ASA GENERATED START ---
// Safe impersonation — hybrid b+c model.
// Admin session stays admin session. Impersonation is server-side context.
// No fake end-user JWT. All impersonated actions are audit-logged.
// --- ASA GENERATED END ---

// --- USER CODE START ---

const IMPERSONATION_COOKIE = 'asa-impersonation-session';
const DEFAULT_TTL_MINUTES = 30;

export interface ImpersonationSession {
  id: string;
  actor_admin_id: string;
  subject_user_id: string;
  reason: string;
  started_at: string;
  expires_at: string;
  stopped_at: string | null;
  is_active: boolean;
}

/**
 * Start impersonation session.
 * Creates DB record + sets HttpOnly cookie.
 */
export async function startImpersonation(
  adminId: string,
  adminEmail: string,
  subjectUserId: string,
  reason: string,
  ttlMinutes: number = DEFAULT_TTL_MINUTES,
): Promise<{ session: ImpersonationSession | null; error?: string }> {
  if (!reason || reason.trim().length < 3) {
    return { session: null, error: 'Reason is required (min 3 characters)' };
  }

  const supabase = createAdminClient();

  // Check if admin already has an active impersonation
  const { data: existing } = await supabase
    .from('impersonation_sessions')
    .select('id')
    .eq('actor_admin_id', adminId)
    .eq('is_active', true)
    .limit(1);

  if (existing && existing.length > 0) {
    return { session: null, error: 'You already have an active impersonation session. Stop it first.' };
  }

  const expiresAt = new Date(Date.now() + ttlMinutes * 60 * 1000).toISOString();

  const { data, error } = await supabase
    .from('impersonation_sessions')
    .insert({
      actor_admin_id: adminId,
      subject_user_id: subjectUserId,
      reason: reason.trim(),
      expires_at: expiresAt,
    })
    .select()
    .single();

  if (error || !data) {
    return { session: null, error: error?.message ?? 'Failed to create impersonation session' };
  }

  // Set HttpOnly cookie with session ID
  const cookieStore = await cookies();
  cookieStore.set(IMPERSONATION_COOKIE, data.id, {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'lax',
    maxAge: ttlMinutes * 60,
    path: '/',
  });

  // Audit log
  await logAuditEvent({
    actor_id: adminId,
    actor_email: adminEmail,
    subject_id: subjectUserId,
    action: 'impersonation.start',
    reason: reason.trim(),
    impersonation_session_id: data.id,
  });

  return { session: data as ImpersonationSession };
}

/**
 * Stop impersonation session.
 */
export async function stopImpersonation(
  adminId: string,
  adminEmail: string,
): Promise<{ success: boolean; error?: string }> {
  const supabase = createAdminClient();

  const { data: session } = await supabase
    .from('impersonation_sessions')
    .select('id, subject_user_id, reason')
    .eq('actor_admin_id', adminId)
    .eq('is_active', true)
    .single();

  if (!session) {
    return { success: false, error: 'No active impersonation session found' };
  }

  await supabase
    .from('impersonation_sessions')
    .update({ stopped_at: new Date().toISOString() })
    .eq('id', session.id);

  // Clear cookie
  const cookieStore = await cookies();
  cookieStore.delete(IMPERSONATION_COOKIE);

  // Audit log
  await logAuditEvent({
    actor_id: adminId,
    actor_email: adminEmail,
    subject_id: session.subject_user_id,
    action: 'impersonation.stop',
    reason: session.reason,
    impersonation_session_id: session.id,
  });

  return { success: true };
}

/**
 * Get current active impersonation session from cookie.
 * Returns null if no active impersonation.
 */
export async function getActiveImpersonation(): Promise<ImpersonationSession | null> {
  const cookieStore = await cookies();
  const sessionId = cookieStore.get(IMPERSONATION_COOKIE)?.value;

  if (!sessionId) return null;

  const supabase = createAdminClient();
  const { data } = await supabase
    .from('impersonation_sessions')
    .select('*')
    .eq('id', sessionId)
    .eq('is_active', true)
    .single();

  if (!data) {
    // Cookie exists but session expired/stopped — clear cookie
    cookieStore.delete(IMPERSONATION_COOKIE);
    return null;
  }

  return data as ImpersonationSession;
}

// --- USER CODE END ---
