import { compare } from 'bcryptjs';
import { eq } from 'drizzle-orm';
import NextAuth from 'next-auth';
import Credentials from 'next-auth/providers/credentials';
import { z } from 'zod';
import { memberships, organizations, users } from '@/db/schema';
import {
  getDefaultBusinessRole,
  isSystemRole
} from '@/lib/auth/rbac';
import { resolveCrmMembershipAccess } from '@/lib/auth/crm-access';
import { db } from '@/lib/db';

const signInSchema = z.object({
  email: z.string().email(),
  password: z.string().min(8)
});

const authSecret =
  process.env.AUTH_SECRET ??
  process.env.NEXTAUTH_SECRET ??
  (process.env.NODE_ENV !== 'production' ? 'dev-only-auth-secret-change-me' : undefined);

type SessionOrganization = {
  id: string;
  name: string;
  slug: string;
  role: string;
  businessRole: string;
  branchScopeIds: string[];
  productTypeScopeIds: string[];
  ownershipScope: string;
  plan: string;
  imageUrl: string | null;
};

async function buildUserAccessContext(userId: string) {
  const dbUser = await db.query.users.findFirst({
    where: eq(users.id, userId)
  });

  if (!dbUser) {
    return null;
  }

  const membershipRows = await db
    .select({
      organizationId: memberships.organizationId,
      role: memberships.role,
      businessRole: memberships.businessRole,
      permissions: memberships.permissions,
      branchScopeIds: memberships.branchScopeIds,
      productTypeScopeIds: memberships.productTypeScopeIds,
      name: organizations.name,
      slug: organizations.slug,
      plan: organizations.plan,
      imageUrl: organizations.imageUrl
    })
    .from(memberships)
    .innerJoin(organizations, eq(organizations.id, memberships.organizationId))
    .where(eq(memberships.userId, dbUser.id));

  const systemRole = isSystemRole(dbUser.systemRole) ? dbUser.systemRole : 'user';
  const rows =
    systemRole === 'super_admin'
      ? (await db.select().from(organizations)).map((organization) => {
          const membership = membershipRows.find(
            (row) => row.organizationId === organization.id
          );

          return {
            organizationId: organization.id,
            role: membership?.role ?? 'admin',
            businessRole: membership?.businessRole ?? getDefaultBusinessRole('admin'),
            permissions: membership?.permissions ?? [],
            branchScopeIds: membership?.branchScopeIds ?? [],
            productTypeScopeIds: membership?.productTypeScopeIds ?? [],
            name: organization.name,
            slug: organization.slug,
            plan: organization.plan,
            imageUrl: organization.imageUrl
          };
        })
      : membershipRows;

  const activeMembership =
    rows.find((row) => row.organizationId === dbUser.activeOrganizationId) ?? rows[0] ?? null;

  if (!dbUser.activeOrganizationId && activeMembership) {
    await db
      .update(users)
      .set({ activeOrganizationId: activeMembership.organizationId })
      .where(eq(users.id, dbUser.id));
  }

  const sessionOrganizations: SessionOrganization[] = [];

  for (const row of rows) {
    const resolvedAccess = await resolveCrmMembershipAccess({
      systemRole,
      organizationId: row.organizationId,
      membership: {
        id: '',
        userId: dbUser.id,
        organizationId: row.organizationId,
        role: row.role,
        businessRole: row.businessRole,
        permissions: row.permissions,
        branchScopeIds: row.branchScopeIds ?? [],
        productTypeScopeIds: row.productTypeScopeIds ?? [],
        createdAt: new Date(),
        updatedAt: new Date()
      }
    });

    sessionOrganizations.push({
      id: row.organizationId,
      name: row.name,
      slug: row.slug,
      role: row.role,
      businessRole: row.businessRole,
      branchScopeIds: resolvedAccess.branchScopeIds,
      productTypeScopeIds: resolvedAccess.productTypeScopeIds,
      ownershipScope: resolvedAccess.ownershipScope,
      plan: row.plan,
      imageUrl: row.imageUrl
    });
  }

  const activeMembershipAccess = activeMembership
    ? await resolveCrmMembershipAccess({
        systemRole,
        organizationId: activeMembership.organizationId,
        membership: {
          id: '',
          userId: dbUser.id,
          organizationId: activeMembership.organizationId,
          role: activeMembership.role,
          businessRole: activeMembership.businessRole,
          permissions: activeMembership.permissions,
          branchScopeIds: activeMembership.branchScopeIds ?? [],
          productTypeScopeIds: activeMembership.productTypeScopeIds ?? [],
          createdAt: new Date(),
          updatedAt: new Date()
        }
      })
    : null;

  return {
    dbUser,
    sessionOrganizations,
    activeMembership,
    activeMembershipAccess
  };
}

export const { handlers, auth, signIn, signOut } = NextAuth({
  trustHost: true,
  secret: authSecret,
  pages: {
    signIn: '/auth/sign-in'
  },
  session: {
    strategy: 'jwt'
  },
  providers: [
    Credentials({
      credentials: {
        email: { label: 'Email', type: 'email' },
        password: { label: 'Password', type: 'password' }
      },
      authorize: async (credentials) => {
        const parsed = signInSchema.safeParse(credentials);

        if (!parsed.success) {
          return null;
        }

        const user = await db.query.users.findFirst({
          where: eq(users.email, parsed.data.email.toLowerCase())
        });

        if (!user) {
          return null;
        }

        const isValid = await compare(parsed.data.password, user.passwordHash);

        if (!isValid) {
          return null;
        }

        return {
          id: user.id,
          name: user.name,
          email: user.email,
          image: user.image,
          systemRole: isSystemRole(user.systemRole) ? user.systemRole : 'user',
          activeOrganizationId: user.activeOrganizationId
        };
      }
    })
  ],
  callbacks: {
    jwt: async ({ token, user }) => {
      if (user) {
        token.sub = user.id;
      }

      if (!token.sub) {
        return token;
      }

      const accessContext = await buildUserAccessContext(token.sub);

      if (!accessContext) {
        return token;
      }

      const { dbUser, sessionOrganizations, activeMembership, activeMembershipAccess } = accessContext;
      const systemRole = isSystemRole(dbUser.systemRole) ? dbUser.systemRole : 'user';

      token.name = dbUser.name;
      token.email = dbUser.email;
      token.picture = dbUser.image ?? null;
      token.systemRole = systemRole;
      token.activeOrganizationId = activeMembership?.organizationId ?? null;
      token.activeOrganizationName = activeMembership?.name ?? null;
      token.activeOrganizationPlan = activeMembership?.plan ?? null;
      token.activeMembershipRole = activeMembership?.role ?? null;
      token.activeBusinessRole = activeMembership?.businessRole ?? null;
      token.activePermissions = activeMembershipAccess?.permissions ?? [];
      token.activeBranchScopeIds = activeMembershipAccess?.branchScopeIds ?? [];
      token.activeProductTypeScopeIds = activeMembershipAccess?.productTypeScopeIds ?? [];
      token.activeOwnershipScope = activeMembershipAccess?.ownershipScope ?? null;
      token.organizations = sessionOrganizations;

      return token;
    },
    session: async ({ session, token }) => {
      if (!token.sub || !session.user) {
        return session;
      }

      session.user.id = token.sub;
      session.user.name = token.name ?? session.user.name ?? null;
      session.user.email = token.email ?? session.user.email ?? null;
      session.user.image = typeof token.picture === 'string' ? token.picture : null;
      session.user.systemRole = token.systemRole === 'super_admin' ? 'super_admin' : 'user';
      session.user.activeOrganizationId =
        typeof token.activeOrganizationId === 'string' ? token.activeOrganizationId : null;
      session.user.activeOrganizationName =
        typeof token.activeOrganizationName === 'string' ? token.activeOrganizationName : null;
      session.user.activeOrganizationPlan =
        typeof token.activeOrganizationPlan === 'string' ? token.activeOrganizationPlan : null;
      session.user.activeMembershipRole =
        typeof token.activeMembershipRole === 'string' ? token.activeMembershipRole : null;
      session.user.activeBusinessRole =
        typeof token.activeBusinessRole === 'string' ? token.activeBusinessRole : null;
      session.user.activePermissions = Array.isArray(token.activePermissions)
        ? token.activePermissions.filter((value): value is string => typeof value === 'string')
        : [];
      session.user.activeBranchScopeIds = Array.isArray(token.activeBranchScopeIds)
        ? token.activeBranchScopeIds.filter((value): value is string => typeof value === 'string')
        : [];
      session.user.activeProductTypeScopeIds = Array.isArray(token.activeProductTypeScopeIds)
        ? token.activeProductTypeScopeIds.filter((value): value is string => typeof value === 'string')
        : [];
      session.user.activeOwnershipScope =
        typeof token.activeOwnershipScope === 'string' ? token.activeOwnershipScope : null;
      session.user.organizations = Array.isArray(token.organizations)
        ? token.organizations.filter(
            (value): value is SessionOrganization =>
              typeof value === 'object' &&
              value !== null &&
              typeof value.id === 'string' &&
              typeof value.name === 'string' &&
              typeof value.slug === 'string' &&
              typeof value.role === 'string' &&
              typeof value.businessRole === 'string' &&
              Array.isArray(value.branchScopeIds) &&
              Array.isArray(value.productTypeScopeIds) &&
              typeof value.ownershipScope === 'string' &&
              typeof value.plan === 'string'
          )
        : [];

      return session;
    }
  }
});
