import { storagePut } from "../storage.ts";

export interface SocialProfile {
  avatarUrl?: string;
  displayName?: string;
  bio?: string;
  location?: string;
  company?: string;
  website?: string;
  email?: string;
  socialId: string;
  provider: "google" | "github" | "apple";
  rawData?: Record<string, any>;
}

/**
 * Extract profile information from Google OAuth data
 */
export async function extractGoogleProfile(googleUser: any): Promise<SocialProfile> {
  const profile: SocialProfile = {
    socialId: googleUser.id,
    provider: "google",
    displayName: googleUser.name,
    email: googleUser.email,
    avatarUrl: googleUser.picture,
    rawData: googleUser,
  };

  // Download and store avatar to S3 if available
  if (profile.avatarUrl) {
    try {
      profile.avatarUrl = await downloadAndStoreAvatar(
        profile.avatarUrl,
        `google_${googleUser.id}`
      );
    } catch (error) {
      console.error("[ProfileSync] Failed to download Google avatar:", error);
      // Keep original URL as fallback
    }
  }

  return profile;
}

/**
 * Extract profile information from GitHub OAuth data
 */
export async function extractGithubProfile(githubUser: any): Promise<SocialProfile> {
  const profile: SocialProfile = {
    socialId: githubUser.id.toString(),
    provider: "github",
    displayName: githubUser.name || githubUser.login,
    email: githubUser.email,
    bio: githubUser.bio,
    location: githubUser.location,
    company: githubUser.company,
    website: githubUser.blog,
    avatarUrl: githubUser.avatar_url,
    rawData: githubUser,
  };

  // Download and store avatar to S3 if available
  if (profile.avatarUrl) {
    try {
      profile.avatarUrl = await downloadAndStoreAvatar(
        profile.avatarUrl,
        `github_${githubUser.id}`
      );
    } catch (error) {
      console.error("[ProfileSync] Failed to download GitHub avatar:", error);
      // Keep original URL as fallback
    }
  }

  return profile;
}

/**
 * Extract profile information from Apple OAuth data
 */
export async function extractAppleProfile(appleUser: any, applePayload?: any): Promise<SocialProfile> {
  const profile: SocialProfile = {
    socialId: appleUser.id,
    provider: "apple",
    email: appleUser.email || applePayload?.email,
    displayName: appleUser.name || "Apple User",
    rawData: appleUser,
  };

  // Apple doesn't provide avatar URL in standard flow
  // Users would need to upload manually or we could generate a default avatar

  return profile;
}

/**
 * Download avatar from URL and store to S3
 */
async function downloadAndStoreAvatar(
  avatarUrl: string,
  userId: string
): Promise<string> {
  try {
    // Fetch the avatar image
    const response = await fetch(avatarUrl);

    if (!response.ok) {
      throw new Error(`Failed to fetch avatar: ${response.statusText}`);
    }

    // Get content type
    const contentType = response.headers.get("content-type") || "image/jpeg";

    // Convert to buffer
    const buffer = await response.arrayBuffer();

    // Generate unique filename
    const extension = contentType.split("/")[1] || "jpg";
    const filename = `avatars/${userId}-${Date.now()}.${extension}`;

    // Upload to S3
    const { url } = await storagePut(filename, Buffer.from(buffer), contentType);

    return url;
  } catch (error) {
    console.error("[ProfileSync] Error downloading/storing avatar:", error);
    throw error;
  }
}

/**
 * Generate default avatar for users without social profile picture
 */
export function generateDefaultAvatar(userId: number, displayName: string): string {
  // Use a service like DiceBear to generate avatars
  const initials = displayName
    .split(" ")
    .slice(0, 2)
    .map((n) => n[0])
    .join("")
    .toUpperCase();

  // DiceBear API for avatar generation
  const seed = `${userId}-${displayName}`;
  return `https://api.dicebear.com/7.x/avataaars/svg?seed=${encodeURIComponent(seed)}&scale=80`;
}

/**
 * Merge social profile data with existing user data
 */
export function mergeProfileData(
  existingData: Record<string, any> = {},
  socialProfile: SocialProfile
): Record<string, any> {
  return {
    ...existingData,
    provider: socialProfile.provider,
    socialId: socialProfile.socialId,
    displayName: socialProfile.displayName || existingData.displayName,
    bio: socialProfile.bio || existingData.bio,
    location: socialProfile.location || existingData.location,
    company: socialProfile.company || existingData.company,
    website: socialProfile.website || existingData.website,
    email: socialProfile.email || existingData.email,
    lastSyncedAt: new Date().toISOString(),
  };
}

/**
 * Update user profile from social provider
 */
export async function syncUserProfileFromProvider(
  userId: number,
  socialProfile: SocialProfile,
  updateUser: (id: number, data: any) => Promise<any>
): Promise<any> {
  try {
    const profileData = mergeProfileData({}, socialProfile);

    const updatedUser = await updateUser(userId, {
      name: socialProfile.displayName,
      avatarUrl: socialProfile.avatarUrl,
      socialProvider: socialProfile.provider,
      socialId: socialProfile.socialId,
      socialProfileData: profileData,
    });

    console.log(
      `[ProfileSync] Successfully synced profile for user ${userId} from ${socialProfile.provider}`
    );

    return updatedUser;
  } catch (error) {
    console.error("[ProfileSync] Failed to sync user profile:", error);
    throw error;
  }
}
