import type { ImportResult } from "@/features/blog-import/types";
import { laravelApis } from "@/lib/laravel-cms/environment";
import { decryptRncryptor } from "@/lib/laravel-cms/rncryptor";

/*
 * Client for the Laravel blog CMS (https://secondphonenumber.worksqr.com), the
 * backend replacing this admin panel. It covers every request in the Laravel
 * team's Postman collection "Second Phone Number - Blog CMS API":
 *
 *   Public (no token, responses encrypted with RNCryptor v3)
 *     GET  v1/posts?page=&perPage=&category=   list
 *     GET  v1/posts/{slug}                      one article (or encrypted 404)
 *     GET  v1/sitemap
 *     GET  v1/preview/{token}
 *   Admin (Authorization: Bearer <token from login>)
 *     POST admin/auth/login                     {email, password} → {ok, token, user}
 *     GET  admin/auth/me
 *     GET  admin/blogs?page=&pageSize=          Laravel paginator
 *     POST admin/blogs                          {intent, values} → {ok, message, data}; values may
 *                                               carry Base64 images (featuredImage, contentImages)
 *     POST admin/blogs/{id}/active|inactive     show or hide an article → {ok, data: {is_active}}
 *     DELETE admin/blogs/{id}                   delete permanently (ADMIN)
 *     GET  blog/admin/media?q=&page=&pageSize=  the media library
 *     POST blog/admin/media                     {filename, data: <data URL>, alt, title} → 201 {ok, data}
 *     DELETE blog/admin/media/{id}
 *     POST blog/admin/blogs/import-json         multipart file, existing, dryRun (ADMIN)
 *     POST blog/admin/crypto/encrypt            {plaintext} → {ok, ciphertext} (ADMIN)
 *     POST blog/admin/crypto/decrypt            {ciphertext} → {ok, plaintext} (ADMIN)
 *
 * Paths are relative to the API base URL (`.../api`). The backend mixes
 * `admin/*` and `blog/admin/*`; `paths` below is the one place to change if
 * that is unified. Every request sends `Accept: application/json`: without it
 * Laravel answers an unauthenticated admin call with a 302 to /signup instead
 * of a 401.
 *
 * Used by the admin panel's server code (through `src/lib/cms/api.ts`, which
 * adds the signed-in admin's token) and by scripts/laravel-cms.ts.
 */

export const paths = {
  posts: "v1/posts",
  post: (slug: string) => `v1/posts/${encodeURIComponent(slug)}`,
  sitemap: "v1/sitemap",
  preview: (token: string) => `v1/preview/${encodeURIComponent(token)}`,
  login: "admin/auth/login",
  me: "admin/auth/me",
  blogs: "admin/blogs",
  blog: (id: string) => `admin/blogs/${encodeURIComponent(id)}`,
  blogActive: (id: string, active: boolean) =>
    `admin/blogs/${encodeURIComponent(id)}/${active ? "active" : "inactive"}`,
  media: "blog/admin/media",
  mediaItem: (id: string) => `blog/admin/media/${encodeURIComponent(id)}`,
  importJson: "blog/admin/blogs/import-json",
  encrypt: "blog/admin/crypto/encrypt",
  decrypt: "blog/admin/crypto/decrypt",
} as const;

/** Staging; pass `apiUrl` (see ./environment.ts, CMS_ENV) for another server. */
export const defaultApiUrl = laravelApis.dev;
const timeoutMs = 60_000;

export type AdminUser = {
  id: number;
  email: string;
  name: string;
  role: "ADMIN" | "EDITOR";
  avatarUrl: string | null;
};

export type BlogStatus = "DRAFT" | "SCHEDULED" | "PUBLISHED";

/** A `blog_posts` row as the admin API returns it (snake_case; only the fields this client reads are typed). */
export type AdminBlogRow = {
  id: string;
  title: string;
  slug: string;
  excerpt: string | null;
  status: BlogStatus;
  published_at: string | null;
  scheduled_at: string | null;
  updated_at: string;
  version: number;
  tags?: { id: string; name: string; slug: string }[];
  [field: string]: unknown;
};

/** Laravel's LengthAwarePaginator JSON. */
export type Paginated<T> = {
  current_page: number;
  data: T[];
  last_page: number;
  per_page: number;
  total: number;
  from: number | null;
  to: number | null;
};

/** The editor's form values (docs/laravel-blog-api.md §8.4); only title is needed for a draft. */
export type BlogValues = {
  title: string;
  slug?: string;
  excerpt?: string;
  content?: string;
  tags?: string[];
  [field: string]: unknown;
};

export type SaveIntent = "draft" | "publish" | "schedule" | "update";

/**
 * An image sent inside a request as Base64, as `POST blog/admin/media` and
 * the image fields of `POST admin/blogs` take it. `data` is a data URL
 * (`data:image/png;base64,…`).
 */
export type Base64Image = {
  filename: string;
  data: string;
  alt?: string;
  title?: string;
};

/** A media-library record as the CMS returns it (either spelling of each field). */
export type MediaRecord = {
  id: string;
  /** As the CMS sent it: absolute, or root-relative to the CMS origin. */
  url: string;
  /** Where the file sits in the CMS's storage, when the CMS says. */
  storageKey: string | null;
  filename: string;
  mimeType: string;
  size: number;
  width: number | null;
  height: number | null;
  alt: string;
  title: string | null;
};

/** The Base64 data URL of some bytes. */
export function toDataUrl(bytes: Uint8Array, mimeType: string) {
  let binary = "";
  // In chunks: String.fromCharCode(...bytes) overflows the stack on large files.
  for (let i = 0; i < bytes.length; i += 0x8000) {
    binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
  }
  return `data:${mimeType};base64,${btoa(binary)}`;
}

const pick = (row: Record<string, unknown>, ...keys: string[]) => {
  for (const key of keys) {
    const value = row[key];
    if (value !== undefined && value !== null && value !== "") return value;
  }
  return null;
};

/** Reads a media row (snake_case or camelCase). Null when it has no URL. */
export function toMediaRecord(row: unknown): MediaRecord | null {
  if (!row || typeof row !== "object") return null;
  const record = row as Record<string, unknown>;
  const url = pick(record, "url", "public_url", "publicUrl", "path");
  if (typeof url !== "string") return null;
  const number = (...keys: string[]) => {
    const value = Number(pick(record, ...keys));
    return Number.isFinite(value) && value > 0 ? value : null;
  };
  const text = (...keys: string[]) => {
    const value = pick(record, ...keys);
    return value === null ? null : String(value);
  };
  return {
    id: text("id") ?? "",
    url,
    storageKey: text("storage_key", "storageKey"),
    filename:
      text("filename", "original_name", "name") ?? url.split("/").pop() ?? "",
    mimeType: text("mime_type", "mimeType") ?? "",
    size: number("size") ?? 0,
    width: number("width"),
    height: number("height"),
    alt: text("alt_text", "altText", "alt") ?? "",
    title: text("title"),
  };
}

/** The record in a media write response: `{data}`, `{data: {media}}`, `{media}` or the row. */
export function mediaRecordFromBody(body: unknown): MediaRecord | null {
  const record = (body ?? {}) as Record<string, unknown>;
  const data = (record.data ?? record) as Record<string, unknown>;
  return toMediaRecord(data?.media ?? record.media ?? data);
}

export type PublicResponse = {
  status: number;
  /** The `X-Blog-Encryption` header, e.g. "rncryptor-v3"; null for plain JSON. */
  encryption: string | null;
  /** The body as sent: ciphertext when encrypted. */
  raw: string;
};

/** An error answer from the CMS, with Laravel's or the blog's field errors. */
export class LaravelCmsError extends Error {
  constructor(
    message: string,
    readonly status: number,
    readonly fieldErrors: Record<string, string> = {},
    readonly body: unknown = null,
    /** "METHOD path" of the request, for logs and "not available" notices. */
    readonly endpoint: string | null = null,
  ) {
    super(message);
    this.name = "LaravelCmsError";
  }

  /**
   * True when the CMS has no such route (or not for this method): the
   * endpoint isn't built yet, as opposed to a record that doesn't exist.
   */
  get missingRoute() {
    if (this.status === 405) return true;
    if (this.status !== 404) return false;
    // Laravel: "The route … could not be found." Symfony: "No route found for …",
    // or its HTML "Not Found" page (a missing record is always a JSON answer).
    return (
      /^The route .* could not be found/i.test(this.message) ||
      /No route found/i.test(this.message) ||
      (this.body === null && /the answer was not JSON$/.test(this.message))
    );
  }
}

/** Reads `{ok:false, error, fieldErrors}` (blog format) or `{message, errors}` (Laravel default). */
function toError(
  status: number,
  body: unknown,
  fallback: string,
  endpoint: string | null = null,
) {
  const record = (body ?? {}) as Record<string, unknown>;
  const message =
    (typeof record.error === "string" && record.error) ||
    (typeof record.message === "string" && record.message) ||
    fallback;
  const fieldErrors: Record<string, string> = {};
  for (const source of [record.fieldErrors, record.errors]) {
    if (!source || typeof source !== "object") continue;
    for (const [field, value] of Object.entries(source)) {
      fieldErrors[field] = Array.isArray(value)
        ? value.join(" ")
        : String(value);
    }
  }
  return new LaravelCmsError(message, status, fieldErrors, body, endpoint);
}

export type RequestOptions = {
  method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
  /** Added to the URL; undefined, null and "" values are left out. */
  query?: Record<string, string | number | boolean | null | undefined>;
  /** Sent as JSON. */
  json?: unknown;
  /** Sent as-is with this content type (the crypto endpoints read the raw body). */
  text?: { body: string; contentType: string };
  form?: FormData;
  auth?: boolean;
};

export type LaravelCmsOptions = {
  /** API base URL, e.g. https://secondphonenumber.worksqr.com/api */
  apiUrl?: string;
  /** Admin API token from login. */
  token?: string | null;
};

export function createLaravelCms(options: LaravelCmsOptions = {}) {
  const apiUrl = (options.apiUrl?.trim() || defaultApiUrl).replace(/\/+$/, "");
  let token = options.token?.trim() || null;

  const url = (path: string) => `${apiUrl}/${path}`;

  async function request<T>(path: string, init: RequestOptions = {}) {
    if (init.query) {
      const params = new URLSearchParams();
      for (const [key, value] of Object.entries(init.query)) {
        if (value !== undefined && value !== null && value !== "") {
          params.set(
            key,
            typeof value === "boolean" ? (value ? "1" : "0") : String(value),
          );
        }
      }
      const search = params.toString();
      if (search) path = `${path}${path.includes("?") ? "&" : "?"}${search}`;
    }
    const headers: Record<string, string> = { accept: "application/json" };
    let body: BodyInit | undefined;
    if (init.json !== undefined) {
      headers["content-type"] = "application/json";
      body = JSON.stringify(init.json);
    } else if (init.text) {
      headers["content-type"] = init.text.contentType;
      body = init.text.body;
    } else if (init.form) {
      body = init.form; // fetch sets the multipart boundary
    }
    if (init.auth !== false) {
      if (!token) {
        throw new LaravelCmsError(
          "Not logged in: log in first or pass an admin token.",
          401,
        );
      }
      headers.authorization = `Bearer ${token}`;
    }

    const method = init.method ?? (body === undefined ? "GET" : "POST");
    const label = `${method} ${path.split("?")[0]}`;
    const response = await fetch(url(path), {
      method,
      headers,
      body,
      redirect: "manual",
      cache: "no-store",
      signal: AbortSignal.timeout(timeoutMs),
    });
    const text = await response.text();
    let parsed: unknown = null;
    try {
      parsed = text ? JSON.parse(text) : null;
    } catch {
      // Not JSON (an HTML error page or a redirect); reported below.
    }

    if (response.status >= 300 && response.status < 400) {
      throw new LaravelCmsError(
        `${label} redirected to ${response.headers.get("location") ?? "another page"} (is the token valid?)`,
        response.status,
        {},
        null,
        label,
      );
    }
    // 204 No Content (e.g. a delete).
    if (response.ok && !text) return {} as T;
    const record = (parsed ?? {}) as Record<string, unknown>;
    if (!response.ok || record.ok === false) {
      throw toError(
        response.status,
        parsed,
        `${label} failed with ${response.status}${parsed === null && text ? ": the answer was not JSON" : ""}`,
        label,
      );
    }
    if (parsed === null) {
      throw new LaravelCmsError(
        `${label}: the answer was not JSON`,
        response.status,
        {},
        null,
        label,
      );
    }
    return parsed as T;
  }

  return {
    apiUrl,
    get token() {
      return token;
    },

    /** Any admin request, authenticated with the token. */
    request,

    // ----- Admin: auth -----

    /** Logs in and keeps the token for later calls. Rate limited (5 per 15 min per email). */
    async login(email: string, password: string) {
      const body = await request<{ token: string; user: AdminUser }>(
        paths.login,
        { json: { email: email.trim().toLowerCase(), password }, auth: false },
      );
      token = body.token;
      return body;
    },

    /** The logged-in admin. Accepts `{user}` and `{data: {user}}`. */
    async me() {
      const body = await request<{
        user?: AdminUser;
        data?: { user?: AdminUser };
      }>(paths.me);
      const user = body.user ?? body.data?.user;
      if (!user)
        throw new LaravelCmsError(
          "GET admin/auth/me returned no user",
          200,
          {},
          body,
        );
      return user;
    },

    // ----- Admin: blogs -----

    /** Articles for the admin list, newest change first. */
    async listBlogs(
      query: {
        page?: number;
        pageSize?: number;
        q?: string;
        status?: BlogStatus;
        categoryId?: string;
        authorId?: string;
        sort?: string;
      } = {},
    ) {
      const params = new URLSearchParams();
      for (const [key, value] of Object.entries({
        ...query,
        page: query.page ?? 1,
        pageSize: query.pageSize ?? 15,
      })) {
        if (value !== undefined && value !== "") params.set(key, String(value));
      }
      const body = await request<{ data: Paginated<AdminBlogRow> }>(
        `${paths.blogs}?${params}`,
      );
      return body.data;
    },

    /** Creates an article. `intent: "draft"` needs only a title. */
    async createBlog(values: BlogValues, intent: SaveIntent = "draft") {
      const body = await request<{ message?: string; data: AdminBlogRow }>(
        paths.blogs,
        {
          json: { intent, values },
        },
      );
      return { message: body.message ?? null, post: body.data };
    },

    /**
     * Shows (`active: true`) or hides an article without changing its
     * status. Returns the row, which carries `is_active`.
     */
    async setBlogActive(id: string, active: boolean) {
      const body = await request<{ message?: string; data?: AdminBlogRow }>(
        paths.blogActive(id, active),
        { method: "POST" },
      );
      return { message: body.message ?? null, post: body.data ?? null };
    },

    /** Deletes an article permanently. ADMIN only; can't be undone. */
    async deleteBlog(id: string) {
      const body = await request<{ message?: string }>(paths.blog(id), {
        method: "DELETE",
      });
      return { message: body.message ?? null };
    },

    // ----- Admin: media -----

    /**
     * Uploads one image to the media library (`POST blog/admin/media`, the
     * file as a Base64 data URL). The CMS checks and stores it and returns
     * its record; use `url` from it in articles.
     */
    async uploadMedia(image: {
      filename: string;
      bytes: Uint8Array;
      mimeType: string;
      alt?: string;
      title?: string;
    }) {
      const body = await request<unknown>(paths.media, {
        json: {
          filename: image.filename,
          data: toDataUrl(image.bytes, image.mimeType),
          ...(image.alt ? { alt: image.alt } : {}),
          ...(image.title ? { title: image.title } : {}),
        },
      });
      const media = mediaRecordFromBody(body);
      if (!media) {
        throw new LaravelCmsError(
          "POST blog/admin/media answered without a media record (no url)",
          200,
          {},
          body,
          "POST blog/admin/media",
        );
      }
      return media;
    },

    /** One page of the media library, newest first. */
    async listMedia(
      query: { q?: string; page?: number; pageSize?: number } = {},
    ) {
      const body = await request<unknown>(paths.media, {
        query: {
          q: query.q,
          page: query.page ?? 1,
          pageSize: query.pageSize ?? 60,
        },
      });
      // `{ok, data: paginator}`, the paginator itself, or a plain array.
      const record = (body ?? {}) as Record<string, unknown>;
      const paginator = (
        "current_page" in record ? record : (record.data ?? record)
      ) as Record<string, unknown> | unknown[];
      const rows = Array.isArray(paginator)
        ? paginator
        : Array.isArray(paginator.data)
          ? paginator.data
          : [];
      const items = rows
        .map(toMediaRecord)
        .filter((item): item is MediaRecord => item !== null);
      const total = Array.isArray(paginator)
        ? items.length
        : Number(paginator.total ?? items.length) || items.length;
      const lastPage = Array.isArray(paginator)
        ? 1
        : Number(paginator.last_page ?? paginator.lastPage ?? 1) || 1;
      return { items, total, lastPage };
    },

    /** Deletes an image from the library and storage. */
    async deleteMedia(id: string) {
      const body = await request<{ message?: string }>(paths.mediaItem(id), {
        method: "DELETE",
      });
      return { message: body.message ?? null };
    },

    /**
     * Uploads a blog export file (docs/blog-export-format.md). Dry run by
     * default: nothing is written until `dryRun: false`. ADMIN only; rate
     * limited (10 per window).
     */
    async importJson(
      file: Blob,
      {
        filename = "blog-export.json",
        existing = "skip",
        dryRun = true,
      }: {
        filename?: string;
        existing?: "skip" | "update";
        dryRun?: boolean;
      } = {},
    ) {
      const form = new FormData();
      form.set("file", file, filename);
      form.set("existing", existing);
      form.set("dryRun", dryRun ? "1" : "0");
      const body = await request<{ message?: string; data: ImportResult }>(
        paths.importJson,
        {
          form,
        },
      );
      return { message: body.message ?? null, result: body.data };
    },

    // ----- Admin: crypto (ADMIN only) -----

    /** Encrypts text with the Blog API key on the server. */
    async encrypt(plaintext: string) {
      const body = await request<{ ciphertext: string }>(paths.encrypt, {
        // Sent exactly as the Postman collection does: a JSON body as text/plain.
        text: {
          body: JSON.stringify({ plaintext }),
          contentType: "text/plain",
        },
      });
      return body.ciphertext;
    },

    /** Decrypts an RNCryptor message (such as a public API response) with the Blog API key on the server. */
    async decrypt(ciphertext: string) {
      const body = await request<{ plaintext: string }>(paths.decrypt, {
        text: {
          body: JSON.stringify({ ciphertext: ciphertext.trim() }),
          contentType: "text/plain",
        },
      });
      return body.plaintext;
    },

    // ----- Public API -----

    /** GETs a public endpoint and returns the body as sent (ciphertext when encrypted). */
    async publicGet(path: string): Promise<PublicResponse> {
      const response = await fetch(url(path), {
        headers: { accept: "application/json" },
        signal: AbortSignal.timeout(timeoutMs),
      });
      return {
        status: response.status,
        encryption: response.headers.get("x-blog-encryption"),
        raw: await response.text(),
      };
    },

    /**
     * Reads a public response as JSON. Decrypts locally when `blogApiKey` is
     * given (what the website does), otherwise through the admin decrypt
     * endpoint (needs an ADMIN token).
     */
    async readPublic(response: PublicResponse, blogApiKey?: string | null) {
      if (!response.encryption) return JSON.parse(response.raw) as unknown;
      if (response.encryption !== "rncryptor-v3") {
        throw new LaravelCmsError(
          `Unknown encryption "${response.encryption}"`,
          response.status,
        );
      }
      const plaintext = blogApiKey
        ? await decryptRncryptor(response.raw, blogApiKey)
        : await this.decrypt(response.raw);
      return JSON.parse(plaintext) as unknown;
    },
  };
}

export type LaravelCms = ReturnType<typeof createLaravelCms>;
