import { Router, type IRouter } from "express";
import bcrypt from "bcryptjs";
import crypto from "node:crypto";
import { and, eq, or, isNull, gt } from "drizzle-orm";
import { db } from "@workspace/db";
import {
  usersTable,
  userRolesTable,
  rolesTable,
  appSettingsTable,
  passwordResetTokensTable,
  groupsTable,
  userGroupsTable,
  auditLogsTable,
} from "@workspace/db";
import { requireAuth, requireAdmin, getUserRoles } from "../middlewares/auth";
import { saveSession, destroySession } from "../lib/session";
import {
  RegisterBody,
  LoginBody,
  UpdateLanguageBody,
  UpdateClockStyleBody,
  UpdateClockHour12Body,
  ForgotPasswordBody,
  ResetPasswordBody,
  VerifyResetTokenBody,
} from "@workspace/api-zod";

const RESET_TOKEN_TTL_MS = 60 * 60 * 1000;

function hashToken(token: string) {
  return crypto.createHash("sha256").update(token).digest("hex");
}

const router: IRouter = Router();

async function getUserGroupsForAuth(
  userId: number,
): Promise<Array<{ id: number; name: string }>> {
  const rows = await db
    .select({ id: groupsTable.id, name: groupsTable.name })
    .from(userGroupsTable)
    .innerJoin(groupsTable, eq(groupsTable.id, userGroupsTable.groupId))
    .where(eq(userGroupsTable.userId, userId));
  return rows;
}

function buildAuthUser(
  user: typeof usersTable.$inferSelect,
  roles: string[],
  groups: Array<{ id: number; name: string }>,
) {
  return {
    id: user.id,
    username: user.username,
    email: user.email,
    displayNameAr: user.displayNameAr,
    displayNameEn: user.displayNameEn,
    preferredLanguage: user.preferredLanguage,
    clockStyle: user.clockStyle,
    clockHour12: user.clockHour12,
    avatarUrl: user.avatarUrl,
    isActive: user.isActive,
    roles,
    groups,
    createdAt: user.createdAt,
  };
}

router.post("/auth/register", async (req, res): Promise<void> => {
  const parsed = RegisterBody.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: parsed.error.message });
    return;
  }

  const [settings] = await db.select().from(appSettingsTable).where(eq(appSettingsTable.id, 1));
  if (settings && !settings.registrationOpen) {
    res.status(403).json({ error: "Registration is closed" });
    return;
  }

  const { username, email, password, displayNameAr, displayNameEn, preferredLanguage } = parsed.data;

  const existing = await db
    .select()
    .from(usersTable)
    .where(eq(usersTable.username, username));

  if (existing.length > 0) {
    res.status(400).json({ error: "Username already taken" });
    return;
  }

  const passwordHash = await bcrypt.hash(password, 10);

  const [user] = await db
    .insert(usersTable)
    .values({
      username,
      email,
      passwordHash,
      displayNameAr: displayNameAr ?? null,
      displayNameEn: displayNameEn ?? null,
      preferredLanguage: preferredLanguage ?? "ar",
    })
    .returning();

  const [userRole] = await db.select().from(rolesTable).where(eq(rolesTable.name, "user"));
  if (userRole) {
    await db.insert(userRolesTable).values({ userId: user.id, roleId: userRole.id });
  }

  // Auto-assign the "Everyone" system group for consistent default linkage
  const [everyoneGroup] = await db
    .select()
    .from(groupsTable)
    .where(eq(groupsTable.name, "Everyone"));
  if (everyoneGroup) {
    await db
      .insert(userGroupsTable)
      .values({ userId: user.id, groupId: everyoneGroup.id })
      .onConflictDoNothing();
  }

  req.session.userId = user.id;
  await saveSession(req);
  const roles = await getUserRoles(user.id);
  res.status(201).json(buildAuthUser(user, roles, await getUserGroupsForAuth(user.id)));
});

router.post("/auth/login", async (req, res): Promise<void> => {
  const parsed = LoginBody.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: parsed.error.message });
    return;
  }

  const { username, password } = parsed.data;

  const [user] = await db
    .select()
    .from(usersTable)
    .where(eq(usersTable.username, username));

  if (!user) {
    res.status(401).json({ error: "Invalid credentials" });
    return;
  }

  const valid = await bcrypt.compare(password, user.passwordHash);
  if (!valid) {
    res.status(401).json({ error: "Invalid credentials" });
    return;
  }

  if (!user.isActive) {
    res.status(401).json({ error: "Account is inactive" });
    return;
  }

  req.session.userId = user.id;
  await saveSession(req);
  const roles = await getUserRoles(user.id);
  res.json(buildAuthUser(user, roles, await getUserGroupsForAuth(user.id)));
});

router.post("/auth/forgot-password", async (req, res): Promise<void> => {
  const parsed = ForgotPasswordBody.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: parsed.error.message });
    return;
  }

  const identifier = parsed.data.identifier.trim();
  const [user] = await db
    .select()
    .from(usersTable)
    .where(or(eq(usersTable.username, identifier), eq(usersTable.email, identifier)));

  if (user && user.isActive) {
    const rawToken = crypto.randomBytes(32).toString("hex");
    const tokenHash = hashToken(rawToken);
    const expiresAt = new Date(Date.now() + RESET_TOKEN_TTL_MS);

    await db.insert(passwordResetTokensTable).values({
      userId: user.id,
      tokenHash,
      expiresAt,
    });

    // No email integration is wired up in this project. The token is intentionally
    // NOT returned to the client — exposing it would defeat the purpose of the
    // reset flow. An admin can fetch the most recent token from the
    // `password_reset_tokens` table to manually deliver the link until an email
    // service is configured. See follow-up task to add email delivery.
    console.log(
      `[auth] Password reset requested for user id=${user.id}; ` +
        `token expires at ${expiresAt.toISOString()}.`,
    );
  }

  res.json({ success: true });
});

router.post("/auth/reset-password/verify", async (req, res): Promise<void> => {
  const parsed = VerifyResetTokenBody.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: parsed.error.message });
    return;
  }

  const tokenHash = hashToken(parsed.data.token);
  const [record] = await db
    .select()
    .from(passwordResetTokensTable)
    .where(
      and(
        eq(passwordResetTokensTable.tokenHash, tokenHash),
        isNull(passwordResetTokensTable.usedAt),
        gt(passwordResetTokensTable.expiresAt, new Date()),
      ),
    );

  res.json({ valid: Boolean(record) });
});

router.post("/auth/reset-password", async (req, res): Promise<void> => {
  const parsed = ResetPasswordBody.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: parsed.error.message });
    return;
  }

  const tokenHash = hashToken(parsed.data.token);
  const [record] = await db
    .select()
    .from(passwordResetTokensTable)
    .where(
      and(
        eq(passwordResetTokensTable.tokenHash, tokenHash),
        isNull(passwordResetTokensTable.usedAt),
        gt(passwordResetTokensTable.expiresAt, new Date()),
      ),
    );

  if (!record) {
    res.status(400).json({ error: "Invalid or expired token" });
    return;
  }

  const passwordHash = await bcrypt.hash(parsed.data.newPassword, 10);

  const now = new Date();

  await db
    .update(usersTable)
    .set({ passwordHash })
    .where(eq(usersTable.id, record.userId));

  // Mark this token used and invalidate any other outstanding reset
  // tokens for the same user so they cannot be replayed.
  await db
    .update(passwordResetTokensTable)
    .set({ usedAt: now })
    .where(
      and(
        eq(passwordResetTokensTable.userId, record.userId),
        isNull(passwordResetTokensTable.usedAt),
      ),
    );

  res.json({ success: true });
});

router.post(
  "/auth/admin/users/:id/issue-reset-link",
  requireAdmin,
  async (req, res): Promise<void> => {
    const userId = Number(req.params.id);
    if (!Number.isInteger(userId)) {
      res.status(400).json({ error: "Invalid user id" });
      return;
    }

    const [user] = await db
      .select()
      .from(usersTable)
      .where(eq(usersTable.id, userId));

    if (!user) {
      res.status(404).json({ error: "User not found" });
      return;
    }

    // Invalidate any outstanding reset tokens for this user so only
    // the newly issued link is usable.
    await db
      .update(passwordResetTokensTable)
      .set({ usedAt: new Date() })
      .where(
        and(
          eq(passwordResetTokensTable.userId, user.id),
          isNull(passwordResetTokensTable.usedAt),
        ),
      );

    const rawToken = crypto.randomBytes(32).toString("hex");
    const tokenHash = hashToken(rawToken);
    const expiresAt = new Date(Date.now() + RESET_TOKEN_TTL_MS);

    await db.insert(passwordResetTokensTable).values({
      userId: user.id,
      tokenHash,
      expiresAt,
    });

    const origin =
      (req.headers["origin"] as string | undefined) ??
      `${req.protocol}://${req.get("host")}`;
    const resetUrl = `${origin.replace(/\/$/, "")}/reset-password?token=${rawToken}`;

    await db.insert(auditLogsTable).values({
      actorUserId: req.session.userId ?? null,
      action: "auth.issue_reset_link",
      targetType: "user",
      targetId: user.id,
      metadata: {
        username: user.username,
        email: user.email,
        expiresAt: expiresAt.toISOString(),
      },
    });

    res.json({ resetUrl, expiresAt: expiresAt.toISOString() });
  },
);

router.post("/auth/logout", async (req, res): Promise<void> => {
  await destroySession(req);
  res.json({ success: true });
});

router.get("/auth/me", requireAuth, async (req, res): Promise<void> => {
  const [user] = await db
    .select()
    .from(usersTable)
    .where(eq(usersTable.id, req.session.userId!));

  if (!user) {
    res.status(401).json({ error: "User not found" });
    return;
  }

  const roles = await getUserRoles(user.id);
  res.json(buildAuthUser(user, roles, await getUserGroupsForAuth(user.id)));
});

router.patch("/auth/me/language", requireAuth, async (req, res): Promise<void> => {
  const parsed = UpdateLanguageBody.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: parsed.error.message });
    return;
  }

  const [user] = await db
    .update(usersTable)
    .set({ preferredLanguage: parsed.data.language })
    .where(eq(usersTable.id, req.session.userId!))
    .returning();

  const roles = await getUserRoles(user.id);
  res.json(buildAuthUser(user, roles, await getUserGroupsForAuth(user.id)));
});

router.patch("/auth/me/clock-hour12", requireAuth, async (req, res): Promise<void> => {
  const parsed = UpdateClockHour12Body.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: parsed.error.message });
    return;
  }

  const [user] = await db
    .update(usersTable)
    .set({ clockHour12: parsed.data.clockHour12 ?? null })
    .where(eq(usersTable.id, req.session.userId!))
    .returning();

  if (!user) {
    res.status(401).json({ error: "User not found" });
    return;
  }

  const roles = await getUserRoles(user.id);
  res.json(buildAuthUser(user, roles, await getUserGroupsForAuth(user.id)));
});

router.patch("/auth/me/clock-style", requireAuth, async (req, res): Promise<void> => {
  const parsed = UpdateClockStyleBody.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ error: parsed.error.message });
    return;
  }

  const [user] = await db
    .update(usersTable)
    .set({ clockStyle: parsed.data.clockStyle ?? null })
    .where(eq(usersTable.id, req.session.userId!))
    .returning();

  if (!user) {
    res.status(401).json({ error: "User not found" });
    return;
  }

  const roles = await getUserRoles(user.id);
  res.json(buildAuthUser(user, roles, await getUserGroupsForAuth(user.id)));
});

export default router;
