/**
 * Prompt Loader — loads AI prompts from the ai_prompts PostgreSQL table.
 */

export async function loadPromptByType(pool, promptType, company = null) {
  try {
    const result = company
      ? await pool.query(
          'SELECT prompt_text FROM ai_prompts WHERE prompt_type = $1 AND company = $2',
          [promptType, company]
        )
      : await pool.query(
          'SELECT prompt_text FROM ai_prompts WHERE prompt_type = $1 AND company IS NULL',
          [promptType]
        );
    return result.rows[0]?.prompt_text || null;
  } catch (error) {
    console.error(`[PromptLoader] Error loading ${promptType} prompt:`, error.message);
    return null;
  }
}

export async function loadPromptsByType(pool, baseType, company = null) {
  const systemType = `${baseType}_system`;
  const generalType = `${baseType}_general`;
  const companyType = `${baseType}_company_specific`;

  const [system, general] = await Promise.all([
    loadPromptByType(pool, systemType),
    loadPromptByType(pool, generalType),
  ]);

  let companySpecific = null;
  if (company) {
    companySpecific = await loadPromptByType(pool, companyType, company);
  }
  return { system, general, companySpecific };
}

export function loadNameValidationPrompts(pool, company = null) {
  return loadPromptsByType(pool, 'name_validation', company);
}

export function loadDescriptionValidationPrompts(pool, company = null) {
  return loadPromptsByType(pool, 'description_validation', company);
}

export function loadSanityCheckPrompts(pool) {
  return loadPromptsByType(pool, 'sanity_check', null);
}

export function loadBulkValidationPrompts(pool, company = null) {
  return loadPromptsByType(pool, 'bulk_validation', company);
}

export async function loadBulkValidationPromptsForCompanies(pool, companyIds = []) {
  const [system, general] = await Promise.all([
    loadPromptByType(pool, 'bulk_validation_system'),
    loadPromptByType(pool, 'bulk_validation_general'),
  ]);

  const companyPrompts = new Map();
  if (companyIds.length > 0) {
    try {
      const result = await pool.query(
        `SELECT company, prompt_text FROM ai_prompts
         WHERE prompt_type = 'bulk_validation_company_specific'
         AND company = ANY($1)`,
        [companyIds]
      );
      for (const row of result.rows) {
        companyPrompts.set(row.company, row.prompt_text);
      }
    } catch (error) {
      console.error('[PromptLoader] Error loading company-specific prompts:', error.message);
    }
  }
  return { system, general, companyPrompts };
}

export function validateRequiredPrompts(prompts, baseType, options = {}) {
  const { requireSystem = true, requireGeneral = true } = options;
  const missing = [];
  if (requireSystem && !prompts.system) missing.push(`${baseType}_system`);
  if (requireGeneral && !prompts.general) missing.push(`${baseType}_general`);
  if (missing.length > 0) {
    throw new Error(
      `Missing required AI prompts: ${missing.join(', ')}. ` +
      `Please add these prompts in Settings > AI Validation Prompts.`
    );
  }
}
