'use server';

import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { getDb, newId, nowIso } from '@/lib/db.js';
import { setItemInstalled, getItem } from '@/lib/marketplace.js';

/**
 * Server action: toggle install state for a marketplace item.
 * Wired into <InstallToggle> via its surrounding <form>.
 *
 * Tool-kind items route to setToolEnabled() under the hood (no behaviour
 * change from the legacy /tools page). Skill items write to
 * marketplace_installations. Bundle items return a deferred status (Phase 2).
 *
 * After the write, redirects back to /marketplace with toast query params
 * so the client banner can confirm the action visually.
 */
export async function toggleInstallAction(formData) {
  const itemId = String(formData.get('item_id') || '');
  const installed = String(formData.get('installed') || 'false') === 'true';
  const currentKind = String(formData.get('current_kind') || '').trim();
  const slugHint = String(formData.get('slug_hint') || '').trim();

  if (!itemId) {
    revalidatePath('/marketplace');
    redirect('/marketplace');
  }

  let toastState = installed ? 'installed' : 'uninstalled';
  let resolvedSlug = slugHint;
  let resolvedKind = '';

  try {
    const before = getItem(itemId);
    if (before) {
      resolvedSlug = resolvedSlug || before.slug || '';
      resolvedKind = before.kind || '';
    }
    const result = setItemInstalled(itemId, installed);
    if (result && typeof result === 'object' && 'status' in result) {
      if (result.status === 'deferred') toastState = 'deferred';
      else if (result.status === 'setup_required') toastState = 'setup_required';
      else if (result.status === 'already_present') toastState = 'already_present';
      else if (result.status === 'in_flight_cases') toastState = 'in_flight_cases';
      else if (result.status === 'error') toastState = 'error';
    }
    if (result && typeof result === 'object' && result.slug) {
      resolvedSlug = resolvedSlug || result.slug;
      resolvedKind = resolvedKind || result.kind || '';
    }
  } catch (err) {
    toastState = 'error';
    auditFailure('marketplace.toggle.failed', { itemId, installed, error: String(err?.message || err) });
  }

  revalidatePath('/marketplace');
  revalidatePath('/tools');

  const params = new URLSearchParams();
  if (currentKind) params.set('kind', currentKind);
  params.set('toast', toastState);
  if (resolvedSlug) params.set('slug', resolvedSlug);
  if (resolvedKind) params.set('toast_kind', resolvedKind);
  redirect(`/marketplace?${params.toString()}`);
}

/**
 * Server action: record that a user clicked "Import from GitHub" in Phase 1.
 * No clone, no install — Phase 2 wires the importer. We log the attempt so
 * the team can quantify demand before shipping the real importer.
 */
export async function recordImportAttemptAction(formData) {
  const url = String(formData.get('url') || '').slice(0, 512);
  auditFailure('marketplace.import.deferred', { url, phase: 1, note: 'Importer ships in Phase 2.' });
  revalidatePath('/marketplace');
  redirect('/marketplace');
}

function auditFailure(type, meta) {
  try {
    getDb().prepare(`
      INSERT INTO audit_logs (id, at, type, summary, status, meta)
      VALUES (?, ?, ?, ?, ?, ?)
    `).run(
      newId('audit'),
      nowIso(),
      type,
      `${type}`,
      'noted',
      JSON.stringify(meta || {}),
    );
  } catch {
    // best-effort — never throw from an audit write
  }
}
