import { OtpPurpose, Role, TenantKind, TenantStatus } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { env } from '../../config/env';
import { hashPassword, verifyPassword } from '../../lib/password';
import { signAccessToken, signRefreshToken } from '../../lib/jwt';
import { alwaysTwoStep, effectivePermissions, PERMISSION_FEATURE } from '../../lib/permissions';
import { FEATURE_KEYS, featuresFor, hasFeature } from '../../lib/tenant-features';
import { ConflictError, ForbiddenError, NotFoundError, UnauthorizedError } from '../../lib/errors';
import { getSupportIdentity } from '../platform/platform.service';
import { issueOtp, openLoginChallenge, recoveryCodesLeft, resendOtp, verifyLoginTotp, verifyOtp, type OtpChallenge } from './two-factor.service';
import type { SignupInput, LoginInput, UpdateProfileInput, ChangePasswordInput } from './auth.schemas';

/** Shape returned to clients — never includes passwordHash. */
export function toPublicUser(u: {
  id: string;
  name: string;
  email: string;
  phone: string | null;
  role: Role;
  tenantId: string | null;
  hasLogin?: boolean;
  staffProfile?: { photoUrl: string | null } | null;
}) {
  return {
    id: u.id,
    name: u.name,
    email: u.email,
    hasLogin: u.hasLogin ?? true,
    phone: u.phone,
    role: u.role,
    tenantId: u.tenantId,
    // Present only where the caller loaded the relation. Staff read their own
    // avatar from here; a student's photo lives on their student profile.
    photoUrl: u.staffProfile?.photoUrl ?? null,
  };
}

type UserWithRole = Parameters<typeof toPublicUser>[0] & {
  customRole?: { permissions: string[] } | null;
  twoFactorEnabled?: boolean;
  totpEnabledAt?: Date | null;
  tenant?: { kind: TenantKind } | null;
};

/**
 * The signed-in user's own shape: public user + the effective permission set
 * the frontend uses to drive nav, + their own 2FA state. Additive fields only,
 * so older clients simply ignore what they do not know.
 */
function publicUserWithPerms(u: UserWithRole) {
  // The tenant's kind rides on the user so the app can shape its navigation
  // from the sign-in response alone. Null for the platform's own admins.
  const kind = u.tenant?.kind ?? null;
  return {
    ...toPublicUser(u),
    perms: effectivePermissions(u.role, u.customRole?.permissions).filter((p) => {
      const feature = PERMISSION_FEATURE[p];
      return !kind || !feature || hasFeature(kind, feature);
    }),
    twoFactorEnabled: u.twoFactorEnabled ?? false,
    // An authenticator app is set up (10 Oct 2026); sign-in then asks for its code.
    totpEnabled: !!u.totpEnabledAt,
    // CRM users and blog editors always sign in with a code; the profile shows it as fixed.
    twoFactorLocked: alwaysTwoStep(u.role),
    tenantKind: kind,
    features: kind ? featuresFor(kind) : [...FEATURE_KEYS],
  };
}

const withCustomRole = {
  customRole: { select: { permissions: true } },
  staffProfile: { select: { photoUrl: true } },
  tenant: { select: { kind: true } },
} as const;

/**
 * Bootstrap the platform's first SUPER_ADMIN. Open signup is allowed ONLY when
 * no SUPER_ADMIN exists yet; after that, additional admins are created by an
 * existing SUPER_ADMIN (and sub-admins by Hostel Admins). This prevents anyone
 * from self-registering as platform staff once the platform is live.
 */
export async function signupSuperAdmin(input: SignupInput) {
  // Hard lock: once ALLOW_SUPER_ADMIN_SIGNUP=false, the endpoint is closed
  // regardless of DB state (defense in depth, even if the row were deleted).
  if (!env.ALLOW_SUPER_ADMIN_SIGNUP) {
    throw new ForbiddenError('Super Admin signup is disabled', 'SIGNUP_DISABLED');
  }
  // Soft lock: only one Super Admin can ever be bootstrapped via open signup.
  const existing = await prismaUnscoped.user.findFirst({ where: { role: Role.SUPER_ADMIN } });
  if (existing) {
    throw new ForbiddenError('A Super Admin already exists; open signup is disabled', 'SIGNUP_CLOSED');
  }

  const emailTaken = await prismaUnscoped.user.findUnique({ where: { email: input.email } });
  if (emailTaken) throw new ConflictError('Email already registered');

  const user = await prismaUnscoped.user.create({
    data: {
      role: Role.SUPER_ADMIN,
      tenantId: null,
      name: input.name,
      email: input.email,
      phone: input.phone,
      passwordHash: await hashPassword(input.password),
    },
  });

  return issueTokensFor(user);
}

/**
 * Whether open Super Admin bootstrap signup is currently available — true only
 * when the flag is on AND no Super Admin exists yet. Used by the frontend to
 * hide the "Create the Super Admin" option. Leaks no user data.
 */
export async function isSignupAvailable(): Promise<boolean> {
  if (!env.ALLOW_SUPER_ADMIN_SIGNUP) return false;
  const existing = await prismaUnscoped.user.findFirst({ where: { role: Role.SUPER_ADMIN } });
  return !existing;
}

/**
 * Refuse to mint a session for a suspended hostel.
 *
 * Enforced at the two points where sessions are created — login and
 * refresh — rather than on every authenticated request, which would cost a
 * tenant lookup per call. A user who is mid-session when their hostel is
 * suspended therefore keeps working until their access token expires; the
 * refresh that follows is what cuts them off. That bounds exposure to one
 * access-token lifetime, which is the right trade for a billing action.
 * A SUPER_ADMIN has no tenantId and is never affected.
 */
async function assertTenantActive(tenantId: string | null) {
  if (!tenantId) return;
  const tenant = await prismaUnscoped.tenant.findUnique({
    where: { id: tenantId },
    select: { status: true, suspendedReason: true },
  });
  if (tenant?.status === TenantStatus.SUSPENDED) {
    const { platformName, supportEmail } = await getSupportIdentity();
    const contact = supportEmail ? `Contact ${supportEmail}.` : `Contact ${platformName} support.`;
    throw new ForbiddenError(
      tenant.suspendedReason
        ? `This hostel account is suspended: ${tenant.suspendedReason}. ${contact}`
        : `This hostel account is suspended. ${contact}`,
    );
  }
}

/**
 * Per-account gates on minting a session, checked at login, at the second
 * sign-in step and at every refresh. Both fields are null on every account
 * that predates them, so for those nothing changes.
 *
 * - `deactivatedAt`: the super admin switched the account off.
 * - `sessionsRevokedAt`: "sign out everywhere" — a token issued before it is void.
 */
export function assertAccountUsable(
  user: { deactivatedAt?: Date | null; sessionsRevokedAt?: Date | null },
  issuedAtSeconds?: number,
) {
  if (user.deactivatedAt) {
    throw new ForbiddenError('This account has been switched off. Contact your administrator.', 'ACCOUNT_DEACTIVATED');
  }
  if (user.sessionsRevokedAt && issuedAtSeconds !== undefined && issuedAtSeconds < Math.floor(user.sessionsRevokedAt.getTime() / 1000)) {
    throw new UnauthorizedError('You were signed out. Please sign in again.');
  }
}

/** The password was right; the account wants a second step before a session. */
export interface TwoFactorRequired extends OtpChallenge {
  twoFactorRequired: true;
  /** Newer clients: how the second step can be passed, and which is asked first. */
  methods?: ('totp' | 'email')[];
  method?: 'totp' | 'email';
}

export type LoginResult = ReturnType<typeof issueTokensFor> | TwoFactorRequired;

export async function login(input: LoginInput): Promise<LoginResult> {
  // Unscoped, pre-auth lookup by globally-unique email.
  const user = await prismaUnscoped.user.findUnique({ where: { email: input.email }, include: withCustomRole });
  // An account registered without a login holds a placeholder address and a
  // password nobody was given; it reads as a wrong password, nothing more.
  if (!user || !user.hasLogin) throw new UnauthorizedError('Invalid email or password');

  const ok = await verifyPassword(input.password, user.passwordHash);
  if (!ok) throw new UnauthorizedError('Invalid email or password');

  await assertTenantActive(user.tenantId);
  assertAccountUsable(user);

  // After the password, so this says nothing about an account to a stranger.
  if (user.tenant?.kind === TenantKind.ENTERPRISE && !input.supportsEnterprise) {
    throw new ForbiddenError('This account is on HostelCare Enterprise. Please update the HostelCare app to sign in, or sign in on the web.', 'ENTERPRISE_APP_UPDATE_REQUIRED');
  }

  // A CRM user always gets a second step, whatever the flag says; so does
  // anyone with an authenticator app set up.
  if (user.twoFactorEnabled || user.totpEnabledAt || alwaysTwoStep(user.role)) {
    // An app build that predates 2FA cannot show a code screen. Say so in
    // the error it already knows how to display, instead of handing it a
    // response without a token.
    if (!input.supportsTwoFactor) {
      throw new ForbiddenError(
        'Two-step verification is turned on for this account. Please update the HostelCare app to sign in, or sign in on the web.',
        'TWO_FACTOR_APP_UPDATE_REQUIRED',
      );
    }
    // With an authenticator app and a client that can ask for it: no email
    // goes out unless the person chooses one. Everyone else: the emailed code.
    if (user.totpEnabledAt && input.supportsTotp) return { twoFactorRequired: true, ...(await openLoginChallenge(user)) };
    const challenge = await issueOtp(user, OtpPurpose.LOGIN);
    return { twoFactorRequired: true, ...challenge, methods: user.totpEnabledAt ? ['email', 'totp'] : ['email'], method: 'email' };
  }
  return completeSignIn(user);
}

/** Second step: the emailed code turns the challenge into a session. */
export async function verifyLoginOtp(challengeId: string, code: string) {
  const userId = await verifyOtp(challengeId, code, OtpPurpose.LOGIN);
  const user = await prismaUnscoped.user.findUnique({ where: { id: userId }, include: withCustomRole });
  if (!user) throw new UnauthorizedError('User no longer exists');
  // The hostel may have been suspended between the two steps.
  await assertTenantActive(user.tenantId);
  assertAccountUsable(user);
  return completeSignIn(user);
}

/** A finished sign-in: stamp it, then hand out the session. */
async function completeSignIn(user: UserWithRole & { id: string }) {
  await prismaUnscoped.user.update({ where: { id: user.id }, data: { lastLoginAt: new Date() } });
  return issueTokensFor(user);
}

/**
 * A hostel admin who just proved their email on the free-trial page (Sprint
 * L2) is signed straight in, exactly as a password sign-in would.
 */
export async function signInNewAccount(userId: string) {
  const user = await prismaUnscoped.user.findUnique({ where: { id: userId }, include: withCustomRole });
  if (!user) throw new UnauthorizedError('User no longer exists');
  return completeSignIn(user);
}

/** Second step by authenticator app, or a recovery code. */
export async function verifyLoginWithTotp(challengeId: string, code: string) {
  const { userId, via } = await verifyLoginTotp(challengeId, code);
  const user = await prismaUnscoped.user.findUnique({ where: { id: userId }, include: withCustomRole });
  if (!user) throw new UnauthorizedError('User no longer exists');
  await assertTenantActive(user.tenantId);
  assertAccountUsable(user);
  const session = await completeSignIn(user);
  return { ...session, usedRecoveryCode: via === 'recovery', recoveryCodesLeft: via === 'recovery' ? await recoveryCodesLeft(userId) : undefined };
}

export function resendLoginOtp(challengeId: string) {
  return resendOtp(challengeId, OtpPurpose.LOGIN);
}

/** Rotate a valid refresh token into a fresh access token. */
export async function refresh(userId: string, issuedAt?: number) {
  const user = await prismaUnscoped.user.findUnique({ where: { id: userId }, include: withCustomRole });
  if (!user) throw new UnauthorizedError('User no longer exists');
  // A refresh token older than the last password change belongs to a session
  // that should have ended when the password was rotated.
  if (user.passwordChangedAt && issuedAt && issuedAt * 1000 < user.passwordChangedAt.getTime()) {
    throw new UnauthorizedError('Password was changed. Please sign in again.');
  }
  assertAccountUsable(user, issuedAt);
  await assertTenantActive(user.tenantId);
  return {
    user: publicUserWithPerms(user),
    accessToken: signAccessToken({ sub: user.id, role: user.role, tenantId: user.tenantId }),
  };
}

export async function getMe(userId: string) {
  const user = await prismaUnscoped.user.findUnique({ where: { id: userId }, include: withCustomRole });
  if (!user) throw new NotFoundError('User not found');
  return publicUserWithPerms(user);
}

function issueTokensFor(user: UserWithRole & { id: string }) {
  return {
    user: publicUserWithPerms(user),
    accessToken: signAccessToken({ sub: user.id, role: user.role, tenantId: user.tenantId }),
    refreshToken: signRefreshToken(user.id),
  };
}

/**
 * Update the signed-in user's own profile.
 *
 * Available to every role — a warden or student changing their own name has
 * nothing to do with SUPER_ADMIN privilege. Email is globally unique, so a
 * clash is a 409 rather than a confusing Prisma error.
 */
export async function updateProfile(userId: string, input: UpdateProfileInput) {
  const user = await prismaUnscoped.user.findUnique({ where: { id: userId } });
  if (!user) throw new NotFoundError('User not found');

  if (input.email && input.email !== user.email) {
    // A CRM user's sign-in codes go to this address, so a borrowed session
    // must not be able to redirect them. The super admin changes it.
    if (alwaysTwoStep(user.role)) {
      throw new ForbiddenError('Ask the super admin to change your email.', 'EMAIL_CHANGE_NOT_ALLOWED');
    }
    const taken = await prismaUnscoped.user.findUnique({ where: { email: input.email } });
    if (taken) throw new ConflictError('That email is already registered');
  }

  const updated = await prismaUnscoped.user.update({
    where: { id: userId },
    data: {
      ...(input.name !== undefined ? { name: input.name } : {}),
      ...(input.email !== undefined ? { email: input.email } : {}),
      // An empty phone means "clear it", which is distinct from "leave it alone".
      ...(input.phone !== undefined ? { phone: input.phone || null } : {}),
    },
    include: withCustomRole,
  });
  return publicUserWithPerms(updated);
}

/**
 * Change the signed-in user's password.
 *
 * Stamps passwordChangedAt, which `refresh` checks against the refresh token's
 * issued-at — so every other signed-in session is cut off at its next refresh.
 * The current password is required, so a hijacked access token alone can't be
 * used to lock the real owner out.
 */
export async function changePassword(userId: string, input: ChangePasswordInput) {
  const user = await prismaUnscoped.user.findUnique({ where: { id: userId } });
  if (!user) throw new NotFoundError('User not found');

  const ok = await verifyPassword(input.currentPassword, user.passwordHash);
  if (!ok) throw new UnauthorizedError('Current password is incorrect');

  const same = await verifyPassword(input.newPassword, user.passwordHash);
  if (same) throw new ConflictError('New password must be different from the current one');

  await prismaUnscoped.user.update({
    where: { id: userId },
    data: { passwordHash: await hashPassword(input.newPassword), passwordChangedAt: new Date() },
  });
}
