import { and, eq } from 'drizzle-orm';
import { NextRequest, NextResponse } from 'next/server';
import { memberships, organizations, users } from '@/db/schema';
import { db } from '@/lib/db';
import { AuthError, requireSession } from '@/lib/auth/session';

export async function PATCH(request: NextRequest) {
  try {
    const session = await requireSession();
    const body = (await request.json()) as { organizationId?: string };
    const organizationId = body.organizationId;

    if (!organizationId) {
      return NextResponse.json({ message: 'organizationId is required' }, { status: 400 });
    }

    if (session.user.systemRole !== 'super_admin') {
      const membership = await db.query.memberships.findFirst({
        where: and(
          eq(memberships.userId, session.user.id),
          eq(memberships.organizationId, organizationId)
        )
      });

      if (!membership) {
        return NextResponse.json({ message: 'Forbidden' }, { status: 403 });
      }
    } else {
      const organization = await db.query.organizations.findFirst({
        where: eq(organizations.id, organizationId)
      });

      if (!organization) {
        return NextResponse.json({ message: 'Organization not found' }, { status: 404 });
      }
    }

    await db
      .update(users)
      .set({ activeOrganizationId: organizationId })
      .where(eq(users.id, session.user.id));

    return NextResponse.json({ success: true });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: 'Unable to switch organization' }, { status: 500 });
  }
}
