/**
 * Seed endpoint — creates containers and initial admin user.
 * POST /api/seed?secret=<SEED_SECRET>
 *
 * Only works when SEED_SECRET env var matches the query param.
 * Disable in production by not setting SEED_SECRET.
 */

import { NextRequest, NextResponse } from 'next/server';
import { logError } from '@/lib/logger';
import { initializeAllContainers } from '@/lib/cosmos';
import { hashPassword } from '@/lib/auth-server';
import { getUserByEmail, createUser } from '@/lib/repositories/users';
import { getRequestProductId } from '@/lib/product-config';
export async function POST(req: NextRequest) {
  try {
    const seedSecret = process.env.SEED_SECRET;
    if (!seedSecret) {
      return NextResponse.json({ error: 'Seeding is disabled' }, { status: 403 });
    }
    const url = new URL(req.url);
    if (url.searchParams.get('secret') !== seedSecret) {
      return NextResponse.json({ error: 'Invalid seed secret' }, { status: 403 });
    }
    // 1. Create all Cosmos DB containers
    await initializeAllContainers();
    // 2. Create default admin user if not exists
    const productId = getRequestProductId(req);
    const adminEmail = 'admin@example.com';
    const existing = await getUserByEmail(adminEmail, productId);
    if (!existing) {
      const now = new Date().toISOString();
      await createUser({
        id: `usr_admin_${Date.now()}`,
        productId,
        email: adminEmail,
        name: 'Admin User',
        passwordHash: await hashPassword('admin123'),
        role: 'super_admin',
        plan: 'enterprise',
        status: 'active',
        createdAt: now,
        lastActive: now,
        totalTokensUsed: 0,
        totalRequests: 0,
        monthlySpend: 0,
      });
    }
    // 3. Create viewer user if not exists
    const viewerEmail = 'viewer@example.com';
    const existingViewer = await getUserByEmail(viewerEmail, productId);
    if (!existingViewer) {
      const now = new Date().toISOString();
      await createUser({
        id: `usr_viewer_${Date.now()}`,
        productId,
        email: viewerEmail,
        name: 'Viewer User',
        passwordHash: await hashPassword('viewer123'),
        role: 'viewer',
        plan: 'free',
        status: 'active',
        createdAt: now,
        lastActive: now,
        totalTokensUsed: 0,
        totalRequests: 0,
        monthlySpend: 0,
      });
    }
    return NextResponse.json({
      success: true,
      message: 'Containers initialized and default users seeded',
    });
  } catch (error) {
    logError('Seed error', error);
    return NextResponse.json({ error: 'Seed failed', details: String(error) }, { status: 500 });
  }
}
