import type { Database } from '../../../../supabase/database.types'
import { encryptCredential, decryptCredential } from './encryption'

type CredentialInsert = Database['public']['Tables']['credentials']['Insert']
type CredentialRow = Database['public']['Tables']['credentials']['Row']

export interface CreateCredentialParams {
  organizationId: string
  name: string
  type: string
  value: Record<string, unknown>
  createdBy: string | null
  provider?: string // OAuth provider ID ('dropbox', 'notion', 'google-sheets')
}

export interface CredentialMetadata {
  id: string
  name: string
  type: string
  provider?: string // OAuth provider ID or undefined for non-OAuth
  createdAt: string
}

/**
 * Prepare credential data for insertion (encrypts the value)
 */
export function prepareCredentialForInsert(
  params: CreateCredentialParams
): Omit<CredentialInsert, 'id' | 'created_at' | 'updated_at'> {
  const encrypted = encryptCredential(JSON.stringify(params.value))

  return {
    organization_id: params.organizationId,
    name: params.name,
    type: params.type,
    encrypted_value: encrypted,
    created_by: params.createdBy,
    provider: params.provider ?? null // Store provider or null for non-OAuth
  }
}

/**
 * Decrypt credential value from database row
 */
export function decryptCredentialValue(encryptedValue: string): Record<string, unknown> {
  return JSON.parse(decryptCredential(encryptedValue))
}

/**
 * Transform database row to metadata (without decrypted value)
 */
export function transformToMetadata(row: CredentialRow): CredentialMetadata {
  return {
    id: row.id,
    name: row.name,
    type: row.type,
    provider: row.provider ?? undefined, // Convert null to undefined
    createdAt: row.created_at
  }
}
