import { FastifyInstance } from "fastify";
import {
  login,
  refreshAccessToken,
  logout,
  verifyAccessToken,
} from "../../services/auth";
import { logAudit } from "../../services/audit";
import { success, error } from "../../utils/response";
import { config } from "../../config/env";
import { LoginRequest, TotpVerifyRequest } from "../../types";
import prisma from "../../config/database";
import crypto from "crypto";
import { OTPAuth } from "../../utils/totp";
import { parseBody } from "../../schemas/common";
import { LoginSchema, TotpVerifySchema } from "../../schemas/auth.schema";

function setRefreshCookie(
  reply: import("fastify").FastifyReply,
  token: string,
  rememberMe: boolean,
) {
  const maxAge = rememberMe
    ? config.jwt.refreshTokenRememberExpiry
    : config.jwt.refreshTokenSessionExpiry;

  reply.setCookie("refresh_token", token, {
    httpOnly: true,
    secure: config.isProduction,
    sameSite: "strict",
    path: "/api/admin",
    maxAge,
  });
}

export default async function authRoutes(
  fastify: FastifyInstance,
): Promise<void> {
  // POST /api/admin/login
  fastify.post<{ Body: LoginRequest }>(
    "/login",
    {
      config: {
        rateLimit: {
          max: config.rateLimit.login,
          timeWindow: "1 minute",
        },
      },
      bodyLimit: 10240,
    },
    async (request, reply) => {
      const parsed = parseBody(LoginSchema, request.body);
      if ("error" in parsed) return error(reply, parsed.error, 400);
      const { username, password, remember_me } = parsed.data;

      const result = await login(username, password, remember_me, request);

      if (result.type === "error") {
        await logAudit({
          request,
          action: "login_failed",
          entityType: "user",
          description: `Neúspěšný pokus o přihlášení: ${username}`,
        });
        return error(reply, result.message, result.status);
      }

      if (result.type === "totp_required") {
        return success(reply, {
          totp_required: true,
          login_token: result.loginToken,
        });
      }

      await logAudit({
        request,
        authData: result.user,
        action: "login",
        entityType: "user",
        entityId: result.user.userId,
        description: `Přihlášení uživatele ${result.user.username}`,
      });

      setRefreshCookie(reply, result.refreshToken, remember_me);
      return success(reply, {
        access_token: result.accessToken,
        expires_in: config.jwt.accessTokenExpiry,
        user: result.user,
      });
    },
  );

  // POST /api/admin/login/totp
  fastify.post<{ Body: TotpVerifyRequest }>(
    "/login/totp",
    {
      config: {
        rateLimit: {
          max: config.rateLimit.loginTotp,
          timeWindow: "1 minute",
        },
      },
      bodyLimit: 10240,
    },
    async (request, reply) => {
      const parsed = parseBody(TotpVerifySchema, request.body);
      if ("error" in parsed) return error(reply, parsed.error, 400);
      const { login_token, totp_code, remember_me } = parsed.data;
      const rememberMe = remember_me ?? false;

      const tokenHash = crypto
        .createHash("sha256")
        .update(login_token)
        .digest("hex");

      const totpResult = await prisma.$transaction(async (tx) => {
        const tokens = await tx.$queryRaw<
          Array<{ id: number; user_id: number; expires_at: Date }>
        >`
          SELECT id, user_id, expires_at FROM totp_login_tokens WHERE token_hash = ${tokenHash} FOR UPDATE
        `;
        const storedToken = tokens[0] ?? null;

        if (!storedToken || new Date(storedToken.expires_at) < new Date()) {
          return { error: "Neplatný nebo expirovaný login token", status: 401 };
        }

        // $queryRaw on MySQL may return BigInt for integer columns
        const storedTokenId = Number(storedToken.id);
        const storedUserId = Number(storedToken.user_id);

        const user = await tx.users.findUnique({
          where: { id: storedUserId },
          include: { roles: true },
        });

        if (!user || !user.totp_secret) {
          return { error: "Uživatel nenalezen", status: 401 };
        }

        if (!user.is_active) {
          return { error: "Účet je deaktivován", status: 401 };
        }

        if (user.locked_until && new Date(user.locked_until) > new Date()) {
          return { error: "Účet je dočasně uzamčen", status: 429 };
        }

        return { user, storedTokenId };
      });

      if ("error" in totpResult) {
        return error(reply, totpResult.error!, totpResult.status!);
      }

      const user = totpResult.user;
      if (!user.totp_secret) {
        return error(reply, "Uživatel nenalezen", 401);
      }

      const verifyResult = OTPAuth.verify(user.totp_secret, totp_code);
      if (!verifyResult.valid) {
        return error(reply, "Neplatný TOTP kód", 401);
      }

      // Reject replayed TOTP codes
      const replayCheck = await prisma.$transaction(async (tx) => {
        const rows = await tx.$queryRaw<
          Array<{ totp_last_used_counter: number | null }>
        >`SELECT totp_last_used_counter FROM users WHERE id = ${user.id} FOR UPDATE`;
        const lastCounter = rows[0]?.totp_last_used_counter ?? null;
        if (
          lastCounter !== null &&
          verifyResult.counter !== null &&
          verifyResult.counter <= lastCounter
        ) {
          return { replay: true };
        }
        await tx.$executeRaw`UPDATE users SET totp_last_used_counter = ${verifyResult.counter} WHERE id = ${user.id}`;
        return { replay: false };
      });

      if (replayCheck.replay) {
        return error(reply, "TOTP kód již byl použit", 401);
      }

      // TOTP verified successfully — now consume the login token
      await prisma.totp_login_tokens.delete({
        where: { id: totpResult.storedTokenId },
      });

      // Reset failed attempts and update last login (TOTP verified = successful login)
      await prisma.users.update({
        where: { id: user.id },
        data: {
          failed_login_attempts: 0,
          locked_until: null,
          last_login: new Date(),
        },
      });

      // Create tokens directly — password was already verified before TOTP was requested
      const authData = await (
        await import("../../services/auth")
      ).loadAuthData(user.id);
      if (!authData) {
        return error(reply, "Chyba načítání uživatele", 500);
      }

      const jwt = await import("jsonwebtoken");
      const accessToken = jwt.default.sign(
        {
          sub: user.id,
          username: user.username,
          role: user.roles?.name ?? null,
        },
        config.jwt.secret,
        { expiresIn: config.jwt.accessTokenExpiry },
      );

      const refreshTokenRaw = crypto.randomBytes(32).toString("hex");
      const refreshTokenHash = crypto
        .createHash("sha256")
        .update(refreshTokenRaw)
        .digest("hex");

      const expiresIn = rememberMe
        ? config.jwt.refreshTokenRememberExpiry
        : config.jwt.refreshTokenSessionExpiry;

      await prisma.refresh_tokens.create({
        data: {
          user_id: user.id,
          token_hash: refreshTokenHash,
          expires_at: new Date(Date.now() + expiresIn * 1000),
          remember_me: rememberMe,
          ip_address: request.ip,
          user_agent: request.headers["user-agent"] ?? null,
        },
      });

      setRefreshCookie(reply, refreshTokenRaw, rememberMe);

      await logAudit({
        request,
        authData: authData,
        action: "login_totp",
        entityType: "user",
        entityId: user.id,
        description: `TOTP přihlášení uživatele ${user.username}`,
      });

      return success(reply, {
        access_token: accessToken,
        expires_in: config.jwt.accessTokenExpiry,
        user: authData,
      });
    },
  );

  // POST /api/admin/refresh
  fastify.post(
    "/refresh",
    {
      config: {
        rateLimit: {
          max: config.rateLimit.refresh,
          timeWindow: "1 minute",
        },
      },
      bodyLimit: 10240,
    },
    async (request, reply) => {
      const refreshTokenRaw = request.cookies.refresh_token;
      if (!refreshTokenRaw) {
        return error(reply, "Refresh token chybí", 401);
      }

      const result = await refreshAccessToken(refreshTokenRaw, request);

      if (result.type === "error") {
        reply.clearCookie("refresh_token", {
          path: "/api/admin",
          httpOnly: true,
          secure: config.isProduction,
          sameSite: "strict",
        });
        return error(reply, result.message, result.status);
      }

      // Preserve the original remember_me flag so long-lived sessions stay long-lived after rotation
      setRefreshCookie(reply, result.refreshToken, result.rememberMe);
      return success(reply, {
        access_token: result.accessToken,
        expires_in: config.jwt.accessTokenExpiry,
        user: result.user,
      });
    },
  );

  // POST /api/admin/logout
  fastify.post("/logout", { bodyLimit: 10240 }, async (request, reply) => {
    const refreshTokenRaw = request.cookies.refresh_token;
    if (refreshTokenRaw) {
      await logout(refreshTokenRaw);
    }

    reply.clearCookie("refresh_token", {
      path: "/api/admin",
      httpOnly: true,
      secure: config.isProduction,
      sameSite: "strict",
    });
    return success(reply, null, 200, "Odhlášení úspěšné");
  });

  // GET /api/admin/session
  fastify.get("/session", async (request, reply) => {
    const authHeader = request.headers.authorization;
    if (!authHeader?.startsWith("Bearer ")) {
      return error(reply, "Vyžadována autentizace", 401);
    }

    const token = authHeader.slice(7);
    const authData = await verifyAccessToken(token);

    if (!authData) {
      return error(reply, "Neplatný token", 401);
    }

    return success(reply, { user: authData });
  });
}
