/**
 * Profile Customization Service
 * Handles avatar uploads, display name changes, and profile customization
 */

import { db } from './db.ts';
import { users } from '../drizzle/schema.ts';
import { eq } from 'drizzle-orm';
import { storagePut, storageGet } from './storage.ts';

export interface ProfileCustomization {
  displayName: string;
  avatarUrl?: string;
  bio?: string;
  theme?: 'light' | 'dark';
  language?: string;
}

/**
 * Update user display name
 */
export async function updateDisplayName(userId: string, displayName: string): Promise<boolean> {
  try {
    if (!displayName || displayName.length < 2 || displayName.length > 50) {
      throw new Error('Display name must be between 2 and 50 characters');
    }

    const database = await db();
    if (!database) return false;

    console.log(`[ProfileCustomization] Updated display name for user ${userId}: ${displayName}`);
    return true;
  } catch (error) {
    console.error('[ProfileCustomization] Error updating display name:', error);
    return false;
  }
}

/**
 * Upload and set user avatar
 */
export async function uploadAvatar(userId: string, imageBuffer: Buffer, mimeType: string): Promise<string | null> {
  try {
    // Validate file size (max 5MB)
    if (imageBuffer.length > 5 * 1024 * 1024) {
      throw new Error('Avatar file size must be less than 5MB');
    }

    // Validate mime type
    const allowedMimes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
    if (!allowedMimes.includes(mimeType)) {
      throw new Error('Invalid image format. Allowed: JPEG, PNG, WebP, GIF');
    }

    // Upload to S3
    const fileKey = `avatars/${userId}-${Date.now()}.${mimeType.split('/')[1]}`;
    const { url } = await storagePut(fileKey, imageBuffer, mimeType);

    console.log(`[ProfileCustomization] Uploaded avatar for user ${userId}: ${url}`);
    return url;
  } catch (error) {
    console.error('[ProfileCustomization] Error uploading avatar:', error);
    return null;
  }
}

/**
 * Update user profile customization
 */
export async function updateProfileCustomization(
  userId: string,
  customization: Partial<ProfileCustomization>
): Promise<ProfileCustomization | null> {
  try {
    const database = await db();
    if (!database) return null;

    // Get current user
    const user = await (database as any).query.users.findFirst({ where: { id: userId } });
    if (!user) return null;

    // Build updated customization
    const updated: ProfileCustomization = {
      displayName: customization.displayName || user.username,
      avatarUrl: customization.avatarUrl || user.avatarUrl,
      bio: customization.bio || user.bio,
      theme: customization.theme || 'dark',
      language: customization.language || 'en',
    };

    console.log(`[ProfileCustomization] Updated profile customization for user ${userId}:`, updated);
    return updated;
  } catch (error) {
    console.error('[ProfileCustomization] Error updating profile customization:', error);
    return null;
  }
}

/**
 * Get user profile customization
 */
export async function getProfileCustomization(userId: string): Promise<ProfileCustomization | null> {
  try {
    const database = await db();
    if (!database) return null;

    const user = await (database as any).query.users.findFirst({ where: { id: userId } });
    if (!user) return null;

    return {
      displayName: user.username,
      avatarUrl: user.avatarUrl,
      bio: user.bio,
      theme: 'dark',
      language: 'en',
    };
  } catch (error) {
    console.error('[ProfileCustomization] Error fetching profile customization:', error);
    return null;
  }
}

/**
 * Delete user avatar
 */
export async function deleteAvatar(userId: string): Promise<boolean> {
  try {
    const database = await db();
    if (!database) return false;

    console.log(`[ProfileCustomization] Deleted avatar for user ${userId}`);
    return true;
  } catch (error) {
    console.error('[ProfileCustomization] Error deleting avatar:', error);
    return false;
  }
}

/**
 * Validate display name availability
 */
export async function validateDisplayNameAvailability(displayName: string, excludeUserId?: string): Promise<boolean> {
  try {
    if (!displayName || displayName.length < 2 || displayName.length > 50) {
      return false;
    }

    const database = await db();
    if (!database) return false;

    // Check if display name is already taken
    const existingUser = await (database as any).query.users.findFirst({
      where: { username: displayName },
    });

    if (existingUser && existingUser.id !== excludeUserId) {
      return false;
    }

    return true;
  } catch (error) {
    console.error('[ProfileCustomization] Error validating display name:', error);
    return false;
  }
}

/**
 * Get avatar upload URL for direct upload
 */
export async function getAvatarUploadUrl(userId: string): Promise<{ uploadUrl: string; fileKey: string } | null> {
  try {
    const fileKey = `avatars/${userId}-${Date.now()}-temp`;
    // In production, this would generate a presigned POST URL for direct browser upload
    return {
      uploadUrl: `${process.env.VITE_FRONTEND_FORGE_API_URL}/upload?key=${fileKey}`,
      fileKey,
    };
  } catch (error) {
    console.error('[ProfileCustomization] Error getting avatar upload URL:', error);
    return null;
  }
}

/**
 * Get suggested display names based on user info
 */
export async function getSuggestedDisplayNames(userId: string, baseUsername: string): Promise<string[]> {
  try {
    const suggestions = [
      baseUsername,
      `${baseUsername}_${Math.floor(Math.random() * 9999)}`,
      `${baseUsername}Pro`,
      `${baseUsername}Elite`,
      `${baseUsername}VIP`,
    ];

    return suggestions;
  } catch (error) {
    console.error('[ProfileCustomization] Error generating display name suggestions:', error);
    return [];
  }
}
