import { and, eq, isNull } from 'drizzle-orm';
import { NextRequest, NextResponse } from 'next/server';
import { memberships, organizations, users } from '@/db/schema';
import { getDefaultPermissionsForRole, isHRD, isSuperAdmin } from '@/lib/auth/roles';
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 });
    }

    const targetOrganization = await db.query.organizations.findFirst({
      where: and(
        eq(organizations.id, organizationId),
        eq(organizations.isActive, true),
        isNull(organizations.deletedAt)
      )
    });

    if (!targetOrganization) {
      return NextResponse.json({ message: 'Organizer not found or inactive' }, { status: 404 });
    }

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

    const canSwitchAnyOrganization =
      isSuperAdmin(session.user.systemRole) ||
      isHRD({
        businessRole: session.user.businessRole,
        systemRole: session.user.systemRole,
        membershipRole: session.user.membershipRole,
        role: session.user.role
      });

    if (!membership && !canSwitchAnyOrganization) {
      return NextResponse.json({ message: 'Forbidden' }, { status: 403 });
    }

    if (!membership && canSwitchAnyOrganization) {
      await db.insert(memberships).values({
        id: crypto.randomUUID(),
        userId: session.user.id,
        organizationId,
        role: 'admin',
        permissions: getDefaultPermissionsForRole('admin')
      });
    }

    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 });
  }
}
