// One-shot: ensure a cloud org + org_membership row exists so the
// requireFreshMembership live check passes for a Supabase-authenticated user.
//
// Usage:
//   node --env-file=.env.local scripts/grant-cloud-membership.mjs <user_id> <org_id> [role]
//
// Defaults: org_id=personal-org, role=owner. The org row is upserted first
// (FK target), then the membership. Idempotent — safe to re-run.

import { isSharedCloudReady, getSharedCloudAdmin } from '../lib/shared-cloud.js';

const userId = process.argv[2];
const orgId = process.argv[3] || 'personal-org';
const role = process.argv[4] || 'owner';

if (!userId) {
  console.error('usage: grant-cloud-membership.mjs <user_id> [org_id] [role]');
  process.exit(1);
}

if (!isSharedCloudReady()) {
  console.error('shared cloud not configured (SUPABASE_URL + SUPABASE_SERVICE_ROLE_KEY missing).');
  process.exit(1);
}

const admin = getSharedCloudAdmin();

// 1. Ensure the organizations row exists (FK target for org_memberships).
const existingOrg = await admin.select('organizations', { filters: { id: orgId }, limit: 1 });
if (!existingOrg.length) {
  await admin.upsert(
    'organizations',
    { id: orgId, slug: orgId, name: 'Personal Org', plan: 'free' },
    { onConflict: 'id' }
  );
  console.log(`organizations: created ${orgId}`);
} else {
  console.log(`organizations: ${orgId} already present`);
}

// 2. Upsert the membership (unique on org_id,user_id).
const membership = await admin.upsert(
  'org_memberships',
  { org_id: orgId, user_id: userId, role, accepted_at: new Date().toISOString() },
  { onConflict: 'org_id,user_id' }
);
console.log('org_memberships upserted:', membership);
