'use server'

import { revalidatePath } from 'next/cache'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { updatePreferencesSchema } from '@/lib/validations/preferences'
import type { ActionResult } from '@/types'

export type UserPreferences = {
  preferredLanguageId: string
  characterDisplay: 'SIMPLIFIED' | 'TRADITIONAL' | 'BOTH'
  transcriptionType: string
  cardsPerSession: number
  dailyGoal: number
  removalThreshold: number
  allowManualDifficulty: boolean
}

export type Language = {
  id: string
  code: string
  name: string
  nativeName: string
}

/**
 * Get user preferences
 */
export async function getPreferences(): Promise<ActionResult<UserPreferences>> {
  try {
    const session = await auth()
    if (!session?.user) {
      return {
        success: false,
        message: 'You must be logged in to view preferences',
      }
    }

    const preference = await prisma.userPreference.findUnique({
      where: { userId: (session.user as any).id },
    })

    if (!preference) {
      return {
        success: false,
        message: 'Preferences not found',
      }
    }

    return {
      success: true,
      data: {
        preferredLanguageId: preference.preferredLanguageId,
        characterDisplay: preference.characterDisplay,
        transcriptionType: preference.transcriptionType,
        cardsPerSession: preference.cardsPerSession,
        dailyGoal: preference.dailyGoal,
        removalThreshold: preference.removalThreshold,
        allowManualDifficulty: preference.allowManualDifficulty,
      },
    }
  } catch (error) {
    console.error('Get preferences error:', error)
    return {
      success: false,
      message: 'An error occurred while fetching preferences',
    }
  }
}

/**
 * Update user preferences
 */
export async function updatePreferences(
  data: Partial<UserPreferences>
): Promise<ActionResult> {
  try {
    const session = await auth()
    if (!session?.user) {
      return {
        success: false,
        message: 'You must be logged in to update preferences',
      }
    }

    // Validate input
    const validatedData = updatePreferencesSchema.parse(data)

    // Update preferences
    await prisma.userPreference.update({
      where: { userId: (session.user as any).id },
      data: validatedData,
    })

    revalidatePath('/settings')

    return {
      success: true,
      message: 'Preferences updated successfully',
    }
  } catch (error: any) {
    if (error.name === 'ZodError') {
      return {
        success: false,
        message: 'Validation failed',
        errors: error.flatten().fieldErrors,
      }
    }

    console.error('Update preferences error:', error)
    return {
      success: false,
      message: 'An error occurred while updating preferences',
    }
  }
}

/**
 * Get available languages
 */
export async function getAvailableLanguages(): Promise<ActionResult<Language[]>> {
  try {
    const languages = await prisma.language.findMany({
      where: { isActive: true },
      select: {
        id: true,
        code: true,
        name: true,
        nativeName: true,
      },
      orderBy: { name: 'asc' },
    })

    return {
      success: true,
      data: languages,
    }
  } catch (error) {
    console.error('Get available languages error:', error)
    return {
      success: false,
      message: 'An error occurred while fetching languages',
    }
  }
}
