// madarX OS — Marketplace per-item REST surface (Phase 1).
//
// PUT  /api/marketplace/[id]   body: { installed: boolean }
//   Tool-kind items proxy to setToolEnabled. Non-tool items write to
//   marketplace_installations. Bundle items return { status: 'deferred' }.
//
// DELETE /api/marketplace/[id]
//   Phase 2 will remove imported items. In Phase 1 this 405s for non-tool
//   items (no item was ever installed externally) and proxies to setToolEnabled
//   with false for tool items.

import { getItem, setItemInstalled } from '../../../../lib/marketplace.js';

export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';

async function readBody(request) {
  try {
    return await request.json();
  } catch {
    return null;
  }
}

export async function PUT(request, context) {
  const params = await Promise.resolve(context.params);
  const id = decodeURIComponent(params.id || '');
  if (!id) return Response.json({ error: 'missing_id' }, { status: 400 });
  const body = await readBody(request);
  if (!body || typeof body.installed !== 'boolean') {
    return Response.json({ error: 'invalid_body', message: 'body.installed must be boolean.' }, { status: 400 });
  }

  const item = getItem(id);
  if (!item) return Response.json({ error: 'not_found' }, { status: 404 });

  try {
    const result = setItemInstalled(id, body.installed);
    if (result && typeof result === 'object' && result.status === 'deferred') {
      return Response.json({ ok: true, deferred: true, ...result }, { status: 200 });
    }
    if (result && typeof result === 'object' && result.status === 'setup_required') {
      return Response.json({
        ok: true,
        setup_required: true,
        ...result,
        setup_endpoint: result.item?.connection?.verify_endpoint || null,
      }, { status: 200 });
    }
    return Response.json({ ok: true, item: result });
  } catch (err) {
    return Response.json(
      { error: 'install_failed', message: String(err?.message || err) },
      { status: 500 },
    );
  }
}

export async function DELETE(_request, context) {
  const params = await Promise.resolve(context.params);
  const id = decodeURIComponent(params.id || '');
  if (!id) return Response.json({ error: 'missing_id' }, { status: 400 });

  const item = getItem(id);
  if (!item) return Response.json({ error: 'not_found' }, { status: 404 });

  if (item.kind === 'connection') {
    return Response.json(
      {
        error: 'delete_redirect',
        message: 'Use DELETE /api/connections/[service] to disconnect a connection.',
        location: `/api/connections/${item.slug}`,
      },
      { status: 405 },
    );
  }

  if (item.kind !== 'tool') {
    return Response.json(
      {
        error: 'delete_not_supported',
        message: 'DELETE for skill/bundle items lands in Phase 2 (importer removal).',
      },
      { status: 405 },
    );
  }

  try {
    const result = setItemInstalled(id, false);
    return Response.json({ ok: true, item: result });
  } catch (err) {
    return Response.json(
      { error: 'uninstall_failed', message: String(err?.message || err) },
      { status: 500 },
    );
  }
}
