/**
 * GET  /api/orgs/[id]/members — list members (requires member+)
 * POST /api/orgs/[id]/members — invite/add a member (requires admin+)
 */

import { requireSession, requireFreshMembership } from '@/lib/auth.js';
import { requireRole } from '@/lib/authz.js';
import { listMembers, addMember, getMembership } 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, { params }) {
  try {
    const { id: orgId } = await params;
    const session = await requireSession(req);
    await requireFreshMembership(session, orgId);

    // Resolve caller's role in this specific org.
    const callerMembership = getMembership(session.user_id, orgId);
    if (!callerMembership) {
      return Response.json({ error: 'insufficient_role' }, { status: 403 });
    }
    requireRole({ ...session, role: callerMembership.role }, 'member', orgId);

    const members = listMembers(orgId);
    return Response.json({ members });
  } catch (err) {
    if (err.status) {
      return Response.json({ error: err.error }, { status: err.status });
    }
    console.error('GET /api/orgs/[id]/members error:', err);
    return Response.json({ error: 'Failed to list members' }, { status: 500 });
  }
}

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

  try {
    const { id: orgId } = await params;
    const session = await requireSession(req);
    await requireFreshMembership(session, orgId);

    // Resolve caller's role in this org.
    const callerMembership = getMembership(session.user_id, orgId);
    if (!callerMembership) {
      return Response.json({ error: 'insufficient_role' }, { status: 403 });
    }
    requireRole({ ...session, role: callerMembership.role }, 'admin', orgId);

    const { user_id, email, role = 'member' } = body;
    if (!user_id && !email) {
      return Response.json({ error: 'user_id or email is required' }, { status: 400 });
    }

    const db = getDb();
    let targetUserId = user_id;

    // If only email was provided, look up the user by email.
    if (!targetUserId && email) {
      const userRow = db.prepare('SELECT id FROM users WHERE email = ?').get(email);
      if (!userRow) {
        // Create a placeholder user row for the invited user.
        const { newId } = await import('@/lib/db.js');
        targetUserId = newId('usr');
        db.prepare(
          `INSERT INTO users (id, email, display_name, auth_provider, created_at)
           VALUES (?, ?, NULL, 'invited', ?)`
        ).run(targetUserId, email, nowIso());
      } else {
        targetUserId = userRow.id;
      }
    }

    // Ensure user row exists (upsert for known user_ids).
    const userExists = db.prepare('SELECT id FROM users WHERE id = ?').get(targetUserId);
    if (!userExists) {
      db.prepare(
        `INSERT INTO users (id, email, display_name, auth_provider, created_at)
         VALUES (?, ?, NULL, 'invited', ?)`
      ).run(targetUserId, email || '', nowIso());
    }

    const membership = addMember(orgId, targetUserId, role);
    return Response.json({ membership }, { status: 201 });
  } catch (err) {
    if (err.status) {
      return Response.json({ error: err.error }, { status: err.status });
    }
    console.error('POST /api/orgs/[id]/members error:', err);
    return Response.json({ error: 'Failed to add member' }, { status: 500 });
  }
}
