/**
 * app/api/admin/share-links/route.js
 *
 * GET  /api/admin/share-links?creator_id=&artifact_id=
 *   List active (non-revoked) share links for the caller's org.
 *   Optional filters: creator_id, artifact_id.
 *
 * POST /api/admin/share-links?action=revoke-by-user&user_id=<uid>
 *   Bulk-revoke all share links created by a specific user in this org.
 *
 * Owner-only.
 */

import { getDb, nowIso, newId } from '@/lib/db.js';
import { requireSession } from '@/lib/auth.js';
import { requireRole } from '@/lib/authz.js';
import { appendComplianceAudit, ComplianceActions, requestIp, requestUserAgent } from '@/lib/compliance-audit.js';

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

function ownerGuard(req) {
  // Shared auth+role check — returns { session } or throws.
  // Caller awaits this.
  return requireSession(req).then(session => {
    requireRole(session, 'owner');
    return session;
  });
}

export async function GET(req) {
  let session;
  try {
    session = await ownerGuard(req);
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    console.error('GET /api/admin/share-links auth error:', err);
    throw err;
  }

  const { searchParams } = new URL(req.url);
  const creatorId = searchParams.get('creator_id') || null;
  const artifactId = searchParams.get('artifact_id') || null;

  const db = getDb();
  const conditions = ['sl.org_id = ?', 'sl.revoked = 0'];
  const binds = [session.org_id];

  if (creatorId) { conditions.push('sl.created_by = ?'); binds.push(creatorId); }
  if (artifactId) { conditions.push('sl.artifact_id = ?'); binds.push(artifactId); }

  const links = db.prepare(
    `SELECT sl.id, sl.artifact_id, sl.created_by, sl.org_id,
            sl.expires_at, sl.max_views, sl.access_count,
            sl.require_email_otp, sl.created_at,
            a.title AS artifact_title
     FROM artifact_share_links sl
     LEFT JOIN artifacts a ON a.id = sl.artifact_id
     WHERE ${conditions.join(' AND ')}
     ORDER BY sl.created_at DESC
     LIMIT 500`
  ).all(...binds);

  return Response.json({ ok: true, links, total: links.length });
}

export async function POST(req) {
  let session;
  try {
    session = await ownerGuard(req);
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    console.error('POST /api/admin/share-links auth error:', err);
    throw err;
  }

  const { searchParams } = new URL(req.url);
  const action = searchParams.get('action');

  if (action === 'revoke-by-user') {
    const userId = searchParams.get('user_id');
    if (!userId) {
      return Response.json({ error: 'user_id query param is required for revoke-by-user' }, { status: 400 });
    }

    const db = getDb();
    const now = nowIso();

    // Find links to revoke — must be in this org and not already revoked.
    const toRevoke = db.prepare(
      `SELECT id FROM artifact_share_links
       WHERE org_id = ? AND created_by = ? AND revoked = 0`
    ).all(session.org_id, userId);

    if (toRevoke.length === 0) {
      return Response.json({ ok: true, revoked: 0, message: 'No active links found for this user' });
    }

    // Bulk revoke.
    const placeholders = toRevoke.map(() => '?').join(', ');
    const ids = toRevoke.map(r => r.id);
    db.prepare(
      `UPDATE artifact_share_links SET revoked = 1 WHERE id IN (${placeholders})`
    ).run(...ids);

    // Compliance audit: one row per revoked link.
    const ip = requestIp(req);
    const ua = requestUserAgent(req);
    for (const link of toRevoke) {
      try {
        appendComplianceAudit({
          user_id: session.user_id,
          org_id: session.org_id,
          action: ComplianceActions.ARTIFACT_SHARE_LINK_REVOKED,
          action_target_id: link.id,
          action_target_type: 'share_link',
          status: 'success',
          summary: `Share link ${link.id} bulk-revoked by owner (target user: ${userId})`,
          meta: { share_link_id: link.id, revoked_user_id: userId, bulk: true },
          ip,
          user_agent: ua,
        });
      } catch (auditErr) {
        console.error('[share-links] audit write failed:', auditErr.message);
      }
    }

    return Response.json({ ok: true, revoked: toRevoke.length });
  }

  return Response.json({ error: `Unknown action: ${action}. Supported: revoke-by-user` }, { status: 400 });
}
