/**
 * GET  /api/orgs — list all orgs for the current session user
 * POST /api/orgs — create a new org (auto-adds caller as owner)
 */

import { getSession } from '@/lib/auth.js';
import { createOrg, listOrgsForUser, addMember } from '@/lib/org.js';
import { getDb, nowIso } from '@/lib/db.js';

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

export async function GET(req) {
  try {
    const session = await getSession(req);
    if (!session) {
      return Response.json({ error: 'unauthenticated' }, { status: 401 });
    }
    const orgs = listOrgsForUser(session.user_id);
    return Response.json({ orgs });
  } catch (err) {
    console.error('GET /api/orgs error:', err);
    return Response.json({ error: 'Failed to list orgs' }, { status: 500 });
  }
}

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

  try {
    const session = await getSession(req);
    if (!session) {
      return Response.json({ error: 'unauthenticated' }, { status: 401 });
    }

    const { slug, name, plan } = body;
    if (!slug || !name) {
      return Response.json({ error: 'slug and name are required' }, { status: 400 });
    }

    // Ensure the calling user exists in the users table (required for FK).
    const db = getDb();
    const existing = db.prepare('SELECT id FROM users WHERE id = ?').get(session.user_id);
    if (!existing) {
      db.prepare(
        `INSERT INTO users (id, email, display_name, auth_provider, created_at)
         VALUES (?, ?, ?, ?, ?)`
      ).run(session.user_id, session.email, session.display_name || null, session.auth_mode, nowIso());
    }

    const org = createOrg({ slug, name, plan });
    addMember(org.id, session.user_id, 'owner');

    // Mirror the new org to the cloud so members can be added to it via the
    // invite RPCs (org_memberships / org_invites both FK → organizations.id).
    // Best-effort: local is the source of truth and must succeed regardless.
    try {
      const { ensureCloudOrg } = await import('@/lib/shared-cloud.js');
      await ensureCloudOrg(org);
    } catch (cloudErr) {
      console.warn('[orgs] cloud org sync failed (local create succeeded):', cloudErr.message);
    }

    return Response.json({ org }, { status: 201 });
  } catch (err) {
    if (err.message?.includes('UNIQUE constraint')) {
      return Response.json({ error: 'An org with that slug already exists.' }, { status: 409 });
    }
    console.error('POST /api/orgs error:', err);
    return Response.json({ error: 'Failed to create org' }, { status: 500 });
  }
}
