import { BlogPostStatus, Prisma, type BlogBuild, type BlogPost } from '@prisma/client';
import { prismaUnscoped as db } from '../../lib/prisma';
import { env } from '../../config/env';
import { BadRequestError, ConflictError, NotFoundError, UnprocessableError } from '../../lib/errors';
import { requestBuild, presentBuild } from './blog-builds.service';
import { mediaUrls, storage } from './blog-media.service';
import { bodyMediaIds, istDate, mediaPath, publishProblems, RESERVED_SLUGS, SLUG_RE, slugify, type PostFields, type Problem } from './blog-rules';

/**
 * Website blog posts (docs/blog-cms-plan.md, B1).
 *
 * Platform-level data: the unscoped client, reached only through
 * requireBlogAccess (SUPER_ADMIN and CONTENT_EDITOR). Publishing marks the
 * post and asks for a website build; the site reads `feed()` when it builds.
 */

export interface Actor {
  id: string;
  name: string;
}

const siteBase = () => env.WEBSITE_URL.replace(/\/$/, '');
export const liveUrl = (slug: string) => `${siteBase()}/resources/blog/${slug}/`;
/** A scheduled time closer than this is "now". */
const NOW_SLACK_MS = 60_000;

/** Stand-ins for the tests. */
export const deps = {
  /** Does the live site already have a page at this address? null = couldn't tell. */
  async siteHasPage(slug: string): Promise<boolean | null> {
    try {
      const res = await fetch(liveUrl(slug), { method: 'HEAD', redirect: 'manual', signal: AbortSignal.timeout(4_000) });
      return res.status === 200;
    } catch {
      return null;
    }
  },
};

// ── Addresses ───────────────────────────────────────────────────────────────

export type SlugVerdict = { slug: string; available: boolean; reason: 'INVALID' | 'RESERVED' | 'TAKEN' | 'ON_SITE' | null };

export async function checkSlug(raw: string, excludeId?: string): Promise<SlugVerdict> {
  const slug = raw.trim().toLowerCase();
  const no = (reason: NonNullable<SlugVerdict['reason']>): SlugVerdict => ({ slug, available: false, reason });
  if (!SLUG_RE.test(slug) || slug.length < 3 || slug.length > 80) return no('INVALID');
  if (RESERVED_SLUGS.has(slug)) return no('RESERVED');
  const clash = await db.blogPost.findFirst({ where: { slug, ...(excludeId ? { id: { not: excludeId } } : {}) }, select: { id: true } });
  if (clash) return no('TAKEN');
  // A page added to the website by hand later is caught here too. If the site
  // can't be reached, the website build's own clash check still stops it.
  if ((await deps.siteHasPage(slug)) === true) return no('ON_SITE');
  return { slug, available: true, reason: null };
}

const SLUG_MESSAGES: Record<NonNullable<SlugVerdict['reason']>, string> = {
  INVALID: 'The address can only have lowercase letters, numbers and single hyphens (3–80 characters).',
  RESERVED: 'That address is already a page on the website.',
  TAKEN: 'That address is already used by another post.',
  ON_SITE: 'That address is already a page on the website.',
};

async function assertSlugFree(slug: string, excludeId?: string) {
  const v = await checkSlug(slug, excludeId);
  if (!v.available) throw new ConflictError(SLUG_MESSAGES[v.reason!], 'SLUG_TAKEN');
}

/** A free address made from the title: "title", "title-2", "title-3"… */
async function freeSlugFrom(title: string): Promise<string> {
  const base = slugify(title).slice(0, 74).replace(/-$/, '') || 'post';
  for (let n = 1; n < 50; n++) {
    const slug = n === 1 ? (base.length >= 3 ? base : `${base}-post`) : `${base}-${n}`;
    if ((await checkSlug(slug)).available) return slug;
  }
  throw new ConflictError('Choose an address for this post.', 'SLUG_TAKEN');
}

// ── Reading ─────────────────────────────────────────────────────────────────

type PostWithBuild = BlogPost & { lastBuild: BlogBuild | null };

async function names(ids: (string | null)[]): Promise<Map<string, string>> {
  const unique = [...new Set(ids.filter((v): v is string => !!v))];
  if (!unique.length) return new Map();
  const rows = await db.user.findMany({ where: { id: { in: unique } }, select: { id: true, name: true } });
  return new Map(rows.map((r) => [r.id, r.name]));
}

/** The library images a post refers to that still exist. */
async function knownMedia(p: { coverMediaId: string | null; bodyMd: string }): Promise<Set<string>> {
  const ids = [...new Set([...(p.coverMediaId ? [p.coverMediaId] : []), ...bodyMediaIds(p.bodyMd)])];
  if (!ids.length) return new Set();
  const rows = await db.blogMedia.findMany({ where: { id: { in: ids } }, select: { id: true } });
  return new Set(rows.map((r) => r.id));
}

const asToc = (v: Prisma.JsonValue): Record<string, string> => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, string>) : {});
const asFaqs = (v: Prisma.JsonValue): { q: string; a: string }[] => (Array.isArray(v) ? (v as { q: string; a: string }[]) : []);
const asCta = (v: Prisma.JsonValue | null): { heading: string; text: string } | null => (v && typeof v === 'object' && !Array.isArray(v) ? (v as { heading: string; text: string }) : null);

function summary(p: PostWithBuild, who: Map<string, string>) {
  return {
    id: p.id,
    slug: p.slug,
    title: p.title,
    status: p.status,
    authorName: p.authorName,
    coverMediaId: p.coverMediaId,
    publishAt: p.publishAt,
    publishedAt: p.publishedAt,
    contentUpdatedAt: p.contentUpdatedAt,
    createdAt: p.createdAt,
    updatedAt: p.updatedAt,
    updatedBy: p.updatedById ? (who.get(p.updatedById) ?? null) : null,
    slugLocked: !!p.publishedAt,
    liveUrl: liveUrl(p.slug),
    build: presentBuild(p.lastBuild),
  };
}

async function present(p: PostWithBuild) {
  const [who, known, urls] = await Promise.all([
    names([p.createdById, p.updatedById]),
    knownMedia(p),
    mediaUrls([...new Set([...(p.coverMediaId ? [p.coverMediaId] : []), ...bodyMediaIds(p.bodyMd)])]),
  ]);
  return {
    ...summary(p, who),
    metaTitle: p.metaTitle,
    description: p.description,
    bodyMd: p.bodyMd,
    coverAlt: p.coverAlt,
    keywords: p.keywords,
    toc: asToc(p.toc),
    faqs: asFaqs(p.faqs),
    cta: asCta(p.cta),
    createdBy: p.createdById ? (who.get(p.createdById) ?? null) : null,
    /** id → ten-minute link, so the editor can show /assets/blog/cms/<id>.webp images. */
    mediaUrls: urls,
    problems: publishProblems(p, known),
  };
}

export type PresentedPost = Awaited<ReturnType<typeof present>>;

async function load(id: string): Promise<PostWithBuild> {
  const p = await db.blogPost.findUnique({ where: { id }, include: { lastBuild: true } });
  if (!p) throw new NotFoundError('Post not found.');
  return p;
}

export async function getPost(id: string) {
  return present(await load(id));
}

export async function listPosts(input: { page: number; limit: number; q?: string; status?: BlogPostStatus }) {
  const where: Prisma.BlogPostWhereInput = {
    ...(input.status ? { status: input.status } : { status: { not: BlogPostStatus.ARCHIVED } }),
    ...(input.q
      ? { OR: [{ title: { contains: input.q, mode: 'insensitive' } }, { slug: { contains: input.q, mode: 'insensitive' } }, { authorName: { contains: input.q, mode: 'insensitive' } }] }
      : {}),
  };
  const [rows, total, counts] = await Promise.all([
    db.blogPost.findMany({ where, include: { lastBuild: true }, orderBy: { updatedAt: 'desc' }, skip: (input.page - 1) * input.limit, take: input.limit }),
    db.blogPost.count({ where }),
    db.blogPost.groupBy({ by: ['status'], _count: { _all: true } }),
  ]);
  const who = await names(rows.map((r) => r.updatedById));
  return {
    items: rows.map((r) => summary(r, who)),
    total,
    page: input.page,
    limit: input.limit,
    hasMore: (input.page - 1) * input.limit + rows.length < total,
    counts: Object.fromEntries(counts.map((c) => [c.status, c._count._all])) as Partial<Record<BlogPostStatus, number>>,
    siteUrl: `${siteBase()}/resources/blog/`,
  };
}

// ── Writing ─────────────────────────────────────────────────────────────────

const CONTENT_KEYS = ['title', 'metaTitle', 'description', 'bodyMd', 'coverMediaId', 'coverAlt', 'authorName', 'keywords', 'toc', 'faqs', 'cta'] as const;

function snapshotOf(p: BlogPost) {
  return {
    slug: p.slug,
    status: p.status,
    publishAt: p.publishAt?.toISOString() ?? null,
    ...Object.fromEntries(CONTENT_KEYS.map((k) => [k, p[k]])),
  } as Prisma.InputJsonObject;
}

async function saveRevision(p: BlogPost, userId: string, note: string) {
  await db.blogPostRevision.create({ data: { postId: p.id, userId, snapshot: snapshotOf(p), note } });
}

/** Prisma's shape for the fields that were sent (absent = unchanged). */
function dataOf(f: PostFields): Prisma.BlogPostUncheckedUpdateInput {
  const d: Prisma.BlogPostUncheckedUpdateInput = {};
  for (const k of CONTENT_KEYS) {
    const v = f[k];
    if (v === undefined) continue;
    if (k === 'cta') d.cta = v === null ? Prisma.DbNull : (v as Prisma.InputJsonObject);
    else (d as Record<string, unknown>)[k] = v;
  }
  return d;
}

async function assertCoverExists(id: string | null | undefined) {
  if (!id) return;
  if (!(await db.blogMedia.findUnique({ where: { id }, select: { id: true } }))) {
    throw new BadRequestError('That cover image is no longer in the image library.', 'MEDIA_NOT_FOUND');
  }
}

function notReady(problems: Problem[], live: boolean): never {
  throw new UnprocessableError(
    live ? 'This post is on the website, so it has to stay ready to publish. Fix these first:' : "The post isn't ready to publish yet.",
    'NOT_READY',
    { problems },
  );
}

export async function createPost(f: PostFields, actor: Actor) {
  if (!f.title) throw new BadRequestError('Give the post a title.', 'TITLE_REQUIRED');
  if (f.slug) await assertSlugFree(f.slug);
  await assertCoverExists(f.coverMediaId);
  const created = await db.blogPost.create({
    data: {
      ...(dataOf(f) as Prisma.BlogPostUncheckedCreateInput),
      title: f.title,
      slug: f.slug ?? (await freeSlugFrom(f.title)),
      authorName: f.authorName ?? actor.name.slice(0, 80),
      status: BlogPostStatus.DRAFT,
      createdById: actor.id,
      updatedById: actor.id,
    },
  });
  await saveRevision(created, actor.id, 'Created');
  return getPost(created.id);
}

export async function updatePost(id: string, f: PostFields, actor: Actor, note = 'Saved') {
  const post = await load(id);
  if (post.status === BlogPostStatus.ARCHIVED) throw new ConflictError('Restore the post before editing it.', 'ARCHIVED');
  if (f.slug !== undefined && f.slug !== post.slug) {
    // Once a post has been on the site its address is fixed: links and
    // search results point at it, and the site has no redirects for it.
    if (post.publishedAt) throw new ConflictError('This post has been on the website, so its address can no longer change.', 'SLUG_LOCKED');
    await assertSlugFree(f.slug, post.id);
  }
  await assertCoverExists(f.coverMediaId);

  const live = post.status === BlogPostStatus.PUBLISHED;
  if (live || post.status === BlogPostStatus.SCHEDULED) {
    const merged = { ...post, ...Object.fromEntries(Object.entries(f).filter(([, v]) => v !== undefined)) } as BlogPost;
    const problems = publishProblems(merged, await knownMedia(merged));
    if (problems.length) notReady(problems, true);
  }

  const saved = await db.blogPost.update({
    where: { id },
    data: { ...dataOf(f), ...(f.slug ? { slug: f.slug } : {}), updatedById: actor.id, ...(live ? { contentUpdatedAt: new Date() } : {}) },
  });
  await saveRevision(saved, actor.id, note);
  // A live post changed: the site needs rebuilding.
  if (live) {
    const build = await requestBuild({ userId: actor.id, reason: `Edited: ${saved.slug}` });
    await db.blogPost.update({ where: { id }, data: { lastBuildId: build.id } });
  }
  return getPost(id);
}

/** Mark a draft as ready for someone else to read, or back. No site change. */
export async function setReview(id: string, review: boolean, actor: Actor) {
  const post = await load(id);
  if (post.status !== BlogPostStatus.DRAFT && post.status !== BlogPostStatus.REVIEW) {
    throw new ConflictError('Only a draft can be sent for review.', 'NOT_DRAFT');
  }
  await db.blogPost.update({ where: { id }, data: { status: review ? BlogPostStatus.REVIEW : BlogPostStatus.DRAFT, updatedById: actor.id } });
  return getPost(id);
}

/** Publish now, or at `publishAt` (scheduled). Everything is checked first. */
export async function publishPost(id: string, publishAt: Date | null, actor: Actor) {
  const post = await load(id);
  if (post.status === BlogPostStatus.ARCHIVED) throw new ConflictError('Restore the post before publishing it.', 'ARCHIVED');
  const problems = publishProblems(post, await knownMedia(post));
  if (problems.length) notReady(problems, false);
  const now = new Date();

  if (publishAt && publishAt.getTime() > now.getTime() + NOW_SLACK_MS) {
    if (post.status === BlogPostStatus.PUBLISHED) throw new ConflictError('This post is already on the website. Unpublish it first to schedule it.', 'ALREADY_LIVE');
    if (publishAt.getTime() > now.getTime() + 366 * 86_400_000) throw new BadRequestError('Schedule a post at most a year ahead.', 'INVALID_DATE');
    const saved = await db.blogPost.update({ where: { id }, data: { status: BlogPostStatus.SCHEDULED, publishAt, updatedById: actor.id } });
    await saveRevision(saved, actor.id, `Scheduled for ${publishAt.toISOString()}`);
    return getPost(id);
  }
  if (post.status === BlogPostStatus.PUBLISHED) return getPost(id);

  const saved = await db.blogPost.update({
    where: { id },
    data: { status: BlogPostStatus.PUBLISHED, publishAt: now, publishedAt: post.publishedAt ?? now, updatedById: actor.id },
  });
  const build = await requestBuild({ userId: actor.id, reason: `Published: ${saved.slug}` });
  await db.blogPost.update({ where: { id }, data: { lastBuildId: build.id } });
  await saveRevision(saved, actor.id, 'Published');
  return getPost(id);
}

/** Take a live or scheduled post off the site (back to a draft). */
export async function unpublishPost(id: string, actor: Actor) {
  const post = await load(id);
  if (post.status !== BlogPostStatus.PUBLISHED && post.status !== BlogPostStatus.SCHEDULED) {
    throw new ConflictError("This post isn't published or scheduled.", 'NOT_PUBLISHED');
  }
  const saved = await db.blogPost.update({ where: { id }, data: { status: BlogPostStatus.DRAFT, updatedById: actor.id } });
  if (post.status === BlogPostStatus.PUBLISHED) {
    const build = await requestBuild({ userId: actor.id, reason: `Unpublished: ${saved.slug}` });
    await db.blogPost.update({ where: { id }, data: { lastBuildId: build.id } });
  }
  await saveRevision(saved, actor.id, 'Unpublished');
  return getPost(id);
}

/** Delete, for an editor: kept with its history so it can be restored. */
export async function archivePost(id: string, actor: Actor) {
  const post = await load(id);
  if (post.status === BlogPostStatus.ARCHIVED) return getPost(id);
  const saved = await db.blogPost.update({ where: { id }, data: { status: BlogPostStatus.ARCHIVED, updatedById: actor.id } });
  if (post.status === BlogPostStatus.PUBLISHED) {
    const build = await requestBuild({ userId: actor.id, reason: `Removed: ${saved.slug}` });
    await db.blogPost.update({ where: { id }, data: { lastBuildId: build.id } });
  }
  await saveRevision(saved, actor.id, 'Deleted');
  return getPost(id);
}

export async function restorePost(id: string, actor: Actor) {
  const post = await load(id);
  if (post.status !== BlogPostStatus.ARCHIVED) throw new ConflictError("This post isn't deleted.", 'NOT_ARCHIVED');
  const saved = await db.blogPost.update({ where: { id }, data: { status: BlogPostStatus.DRAFT, updatedById: actor.id } });
  await saveRevision(saved, actor.id, 'Restored');
  return getPost(id);
}

// ── History ─────────────────────────────────────────────────────────────────

export async function listRevisions(id: string, input: { page: number; limit: number }) {
  await load(id);
  const [rows, total] = await Promise.all([
    db.blogPostRevision.findMany({ where: { postId: id }, orderBy: { createdAt: 'desc' }, skip: (input.page - 1) * input.limit, take: input.limit }),
    db.blogPostRevision.count({ where: { postId: id } }),
  ]);
  const who = await names(rows.map((r) => r.userId));
  return {
    items: rows.map((r) => ({ id: r.id, createdAt: r.createdAt, note: r.note, by: r.userId ? (who.get(r.userId) ?? null) : null, snapshot: r.snapshot })),
    total,
    page: input.page,
    limit: input.limit,
    hasMore: (input.page - 1) * input.limit + rows.length < total,
  };
}

/**
 * Put an earlier version's content back. Status, dates and (once it has been
 * live) the address stay as they are now: restoring old text must not take a
 * live post down or move it. A live post's rules still apply.
 */
export async function restoreRevision(id: string, revisionId: string, actor: Actor) {
  const post = await load(id);
  const rev = await db.blogPostRevision.findFirst({ where: { id: revisionId, postId: id } });
  if (!rev) throw new NotFoundError('That version was not found.');
  const snap = (rev.snapshot ?? {}) as Record<string, unknown>;
  const fields: PostFields = {};
  for (const k of CONTENT_KEYS) if (k in snap) (fields as Record<string, unknown>)[k] = snap[k];
  if (!post.publishedAt && typeof snap.slug === 'string' && snap.slug !== post.slug) fields.slug = snap.slug;
  const when = rev.createdAt.toISOString().slice(0, 16).replace('T', ' ');
  return updatePost(id, fields, actor, `Restored the version from ${when} UTC`);
}

// ── Scheduled posts (the job) ───────────────────────────────────────────────

/** Scheduled posts whose time has come go live, all in one build. */
export async function releaseScheduled(now = new Date()): Promise<number> {
  const due = await db.blogPost.findMany({ where: { status: BlogPostStatus.SCHEDULED, publishAt: { lte: now } } });
  if (!due.length) return 0;
  for (const p of due) {
    const saved = await db.blogPost.update({ where: { id: p.id }, data: { status: BlogPostStatus.PUBLISHED, publishedAt: p.publishedAt ?? now } });
    await db.blogPostRevision.create({ data: { postId: p.id, userId: null, snapshot: snapshotOf(saved), note: 'Went live as scheduled' } });
  }
  const build = await requestBuild({ reason: `Scheduled: ${due.map((p) => p.slug).join(', ')}` });
  await db.blogPost.updateMany({ where: { id: { in: due.map((p) => p.id) } }, data: { lastBuildId: build.id } });
  return due.length;
}

// ── The feed the website build reads ────────────────────────────────────────

/** How long the image links in the feed work: the build downloads them at once. */
const FEED_LINK_SECONDS = 15 * 60;

/**
 * Every post that is live now, in the website's shape, and a download link
 * for every image they use. Drafts, scheduled and deleted posts never appear.
 */
export async function feed() {
  const rows = await db.blogPost.findMany({
    where: { status: BlogPostStatus.PUBLISHED, OR: [{ publishAt: null }, { publishAt: { lte: new Date() } }] },
    orderBy: [{ publishAt: 'desc' }, { createdAt: 'desc' }],
  });
  const ids = [...new Set(rows.flatMap((p) => [...(p.coverMediaId ? [p.coverMediaId] : []), ...bodyMediaIds(p.bodyMd)]))];
  const media = ids.length ? await db.blogMedia.findMany({ where: { id: { in: ids } } }) : [];
  const byId = new Map(media.map((m) => [m.id, m]));

  const posts = rows.map((p) => {
    const shown = p.publishAt ?? p.publishedAt ?? p.createdAt;
    const date = istDate(shown);
    const updated = p.contentUpdatedAt && istDate(p.contentUpdatedAt) !== date ? istDate(p.contentUpdatedAt) : null;
    const cover = p.coverMediaId ? byId.get(p.coverMediaId) : undefined;
    return {
      slug: p.slug,
      title: p.title,
      metaTitle: p.metaTitle,
      description: p.description,
      date,
      updated,
      publishedAt: shown.toISOString(),
      modifiedAt: (p.contentUpdatedAt ?? shown).toISOString(),
      author: p.authorName,
      cover: cover ? { path: mediaPath(cover.id), alt: p.coverAlt ?? '', width: cover.width, height: cover.height } : null,
      keywords: p.keywords,
      toc: asToc(p.toc),
      faqs: asFaqs(p.faqs),
      cta: asCta(p.cta),
      body: p.bodyMd,
    };
  });
  return {
    generatedAt: new Date().toISOString(),
    count: posts.length,
    posts,
    media: await Promise.all(
      media.map(async (m) => ({ id: m.id, path: mediaPath(m.id), mime: m.mime, width: m.width, height: m.height, url: await storage.presign(m.key, FEED_LINK_SECONDS) })),
    ),
  };
}
