const axios = require('axios')
const { getConfig } = require('./config')
const { getToken } = require('./auth')
const { getCodeLibrary, updateCodeLibrary, createVersion: createVersionAPI } = require('./api')

async function getLatestVersion(appId, cid) {
  try {
    const templateLib = await getCodeLibrary(appId, cid)
    // Check if versions exist in the structure
    // For now, we'll track versionCount in metadata
    return templateLib.versionCount || 0
  } catch (error) {
    // If template doesn't exist, start at version 0
    return 0
  }
}

async function createVersion(appId, cid, versionData) {
  // Validate cid is present
  if (!cid) {
    throw new Error('Template ID is required to create a version')
  }

  // Get current version count
  const versionNumber = await getLatestVersion(appId, cid)
  const newVersionNumber = versionNumber + 1

  // Ensure name is always present and is a non-empty string
  const nameValue = (versionData.name && typeof versionData.name === 'string' && versionData.name.trim()) 
    ? versionData.name.trim() 
    : `v${newVersionNumber}`
  
  // Build payload ensuring name is first and always present
  const versionPayload = {
    name: nameValue,
    createdAt: Date.now(),
    updatedAt: Date.now(),
  }
  
  // Add other properties from versionData, but ensure name isn't overwritten
  Object.keys(versionData).forEach(key => {
    if (key !== 'name') {
      versionPayload[key] = versionData[key]
    }
  })

  // Final verification - ensure name is always a valid non-empty string
  if (!versionPayload.name || typeof versionPayload.name !== 'string' || !versionPayload.name.trim()) {
    versionPayload.name = `v${newVersionNumber}`
  }

  try {
    // Use API endpoint instead of direct Firebase access
    const result = await createVersionAPI(appId, cid, versionPayload)
    
    // Update versionCount in template metadata
    await updateCodeLibrary(appId, cid, {
      versionCount: newVersionNumber,
    })

    return {
      versionId: result.id || `v${newVersionNumber}`,
      versionNumber: newVersionNumber,
      ...versionPayload,
    }
  } catch (error) {
    // Provide more detailed error information
    let errorMessage = `Failed to create version: ${error.message}`
    if (error.response) {
      const { status, data } = error.response
      errorMessage = `Failed to create version (${status}): ${data?.message || data?.error || JSON.stringify(data) || error.message}`
    }
    throw new Error(errorMessage)
  }
}

async function getVersions(appId, cid) {
  const config = getConfig()
  const cmsUrl = config.cmsUrl
  const token = await getToken()

  const versionPath = `apps/${appId}/codelibs/${cid}/versions`
  let firebaseUrl = cmsUrl
  if (cmsUrl.includes('/api')) {
    firebaseUrl = cmsUrl.replace('/api', '')
  }
  const databaseUrl = firebaseUrl.includes('firebaseio.com') 
    ? firebaseUrl 
    : firebaseUrl.replace(/\.web\.app$/, '-default-rtdb.firebaseio.com').replace(/\.firebaseapp\.com$/, '-default-rtdb.firebaseio.com')
  
  const versionsUrl = `${databaseUrl}/${versionPath}.json?auth=${token}`

  try {
    const response = await axios.get(versionsUrl)
    return response.data || {}
  } catch (error) {
    // If versions don't exist yet, return empty object
    if (error.response?.status === 404) {
      return {}
    }
    throw new Error(`Failed to get versions: ${error.message}`)
  }
}

module.exports = {
  getLatestVersion,
  createVersion,
  getVersions,
}

