// /api/brand/share — share the local brand profile with the org, or adopt the
// org's shared brand locally.
//
//   GET                      → local share status + capabilities (+ org brand peek)
//   POST { action:'publish'  } → owner/admin: publish local brand to the org cloud row
//   POST { action:'unpublish'} → owner/admin: stop sharing (delete cloud row)
//   POST { action:'adopt'    } → member+: pull the org brand into local config
//
// Local-first: the brand stays in local SQLite by default. Publishing/adopting
// are explicit, audited actions routed through lib/shared-cloud.js, which holds
// the service-role key server-side and never ships it to the browser.

import { getBrandProfile, saveBrandProfile } from '@/lib/brand.js';
import {
  isSharedCloudReady,
  isSharedCloudUserReady,
  getBrandPublishStatus,
  publishBrandProfile,
  unpublishBrandProfile,
  fetchOrgBrandProfile,
  markBrandAdopted,
} from '@/lib/shared-cloud.js';
import { requireSession, requireFreshMembership } from '@/lib/auth.js';

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

function requireManager(session) {
  if (!['owner', 'admin'].includes(session.role)) {
    throw { status: 403, error: 'forbidden' };
  }
}

function cloudReady() {
  return isSharedCloudReady() || isSharedCloudUserReady();
}

export async function GET(req) {
  try {
    const session = await requireSession(req);
    if (!session.org_id) {
      return Response.json({ ok: true, status: { status: 'local', published: false }, can_manage: false, shared_cloud_ready: false, needs_org: true });
    }

    const ready = cloudReady();
    const status = getBrandPublishStatus(session.org_id);
    const canManage = ['owner', 'admin'].includes(session.role);

    // Peek whether an org brand exists so the UI can offer "Adopt". Best-effort:
    // a network hiccup must never break the page, so failures degrade to null.
    let orgBrand = null;
    if (ready) {
      try {
        const fetched = await fetchOrgBrandProfile({ session, org_id: session.org_id });
        if (fetched) {
          orgBrand = {
            company_name: fetched.company_name,
            content_hash: fetched.content_hash,
            updated_at: fetched.updated_at,
            is_current: fetched.content_hash && fetched.content_hash === status.content_hash,
          };
        }
      } catch {
        orgBrand = null;
      }
    }

    return Response.json({
      ok: true,
      status,
      can_manage: canManage,
      shared_cloud_ready: ready,
      org_brand: orgBrand,
    });
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ ok: false, error: err.error || 'unauthorized' }, { status: err.status });
    }
    return Response.json({ ok: false, error: err?.message || 'server_error' }, { status: 500 });
  }
}

export async function POST(req) {
  let body;
  try {
    body = await req.json();
  } catch {
    return Response.json({ ok: false, error: 'invalid_json' }, { status: 400 });
  }

  try {
    const session = await requireSession(req);
    if (!session.org_id) {
      return Response.json({ ok: false, error: 'org_required' }, { status: 400 });
    }
    await requireFreshMembership(session, session.org_id);

    if (!cloudReady()) {
      return Response.json({ ok: false, error: 'shared_cloud_not_configured' }, { status: 503 });
    }

    const action = String(body?.action || '');

    if (action === 'publish') {
      requireManager(session);
      const profile = getBrandProfile();
      const status = await publishBrandProfile({
        session,
        org_id: session.org_id,
        profile,
        published_by: session.user_id,
      });
      return Response.json({ ok: true, status });
    }

    if (action === 'unpublish') {
      requireManager(session);
      const status = await unpublishBrandProfile({ session, org_id: session.org_id });
      return Response.json({ ok: true, status });
    }

    if (action === 'adopt') {
      const fetched = await fetchOrgBrandProfile({ session, org_id: session.org_id });
      if (!fetched || !fetched.profile) {
        return Response.json({ ok: false, error: 'no_org_brand' }, { status: 404 });
      }
      // Adopt = make the org brand this install's local default. The org's logo
      // data URL rides inside profile_json, so saving the profile is enough.
      const saved = saveBrandProfile({ ...fetched.profile, active: true });
      const status = markBrandAdopted(session.org_id, {
        content_hash: fetched.content_hash,
        user_id: session.user_id,
      });
      return Response.json({ ok: true, status, brand: saved });
    }

    return Response.json({ ok: false, error: 'invalid_action' }, { status: 400 });
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ ok: false, error: err.error || 'unauthorized' }, { status: err.status });
    }
    if (/required|not configured|not found/i.test(String(err?.message || ''))) {
      return Response.json({ ok: false, error: err.message }, { status: 400 });
    }
    return Response.json({ ok: false, error: err?.message || 'server_error' }, { status: 500 });
  }
}
