/**
 * Website blog CMS (docs/blog-cms-plan.md, B1/B2).
 *
 * Runs against its own THROWAWAY schema (hc_blog_test), set up and dropped
 * by `npm run test:isolation` after the isolation test. S3, GitHub and the live-site check are stood in
 * for, so nothing leaves this machine.
 */
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { BlogBuildState, BlogPostStatus, PrismaClient, Role } from '@prisma/client';
import { env } from '../config/env';
import { UnprocessableError, ConflictError, BadRequestError } from '../lib/errors';
import * as posts from '../modules/blog-cms/blog-posts.service';
import * as media from '../modules/blog-cms/blog-media.service';
import * as builds from '../modules/blog-cms/blog-builds.service';
import { github, type GithubRun } from '../modules/blog-cms/blog-github';
import { importDocx, extractCta, extractFaqs, extractSeoTable } from '../modules/blog-cms/blog-docx.service';
import { bodyProblems, istDate, mediaPath, postFieldsSchema, slugify } from '../modules/blog-cms/blog-rules';

const raw = new PrismaClient();

// ── Stand-ins ────────────────────────────────────────────────────────────────
const stored = new Map<string, Buffer>();
media.storage.put = async (key, body) => void stored.set(key, body);
media.storage.presign = async (key) => `https://s3.test/${key}?signed`;
media.storage.remove = async (key) => void stored.delete(key);
const onSite = new Set<string>();
posts.deps.siteHasPage = async (slug) => onSite.has(slug);
const gh = { dispatched: 0, runs: [] as GithubRun[], fail: false };
github.dispatch = async () => {
  if (gh.fail) throw new Error('GitHub 500: down');
  gh.dispatched += 1;
};
github.listDispatchRuns = async () => gh.runs;
github.getRun = async (id) => gh.runs.find((r) => BigInt(r.id) === BigInt(id)) ?? null;

/** The smallest PNG header imageSize() reads: 1200 × 800. */
function png(width = 1200, height = 800): Buffer {
  const b = Buffer.alloc(33);
  Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(b, 0);
  b.writeUInt32BE(13, 8);
  b.write('IHDR', 12, 'ascii');
  b.writeUInt32BE(width, 16);
  b.writeUInt32BE(height, 20);
  return b;
}

let editor = { id: '', name: 'Asha Writer' };
const p = (fields: unknown) => postFieldsSchema.parse(fields);

async function readyFields(coverId: string, bodyImageId: string) {
  return p({
    title: 'Hostel Fee Reminders That Get Paid',
    metaTitle: 'Hostel Fee Reminders: A Practical Guide',
    description: 'How hostel owners in India can send fee reminders that get paid on time, with timing and templates that work.',
    keywords: ['hostel fee reminders', 'rent reminder'],
    coverMediaId: coverId,
    coverAlt: 'An owner sending reminders',
    bodyMd: [
      '## Why reminders matter',
      '',
      'Late fees are the most common cash-flow problem for hostel and PG owners. A clear reminder sent at the right time fixes most of it.',
      '',
      `![Reminder screen](${mediaPath(bodyImageId)})`,
      '',
      '## When to send them',
      '',
      'Send the first reminder three days before the due date, then on the day. See [our pricing](/pricing/) or [WhatsApp us](https://wa.me/919999999999).',
    ].join('\n'),
  });
}

test('blog: clean slate and an editor (throwaway schema)', async () => {
  await raw.blogPostRevision.deleteMany({});
  await raw.blogPost.deleteMany({});
  await raw.blogMedia.deleteMany({});
  await raw.blogBuild.deleteMany({});
  await raw.user.deleteMany({ where: { email: { in: ['blog-editor@test.local'] } } });
  const u = await raw.user.create({ data: { role: Role.CONTENT_EDITOR, tenantId: null, name: 'Asha Writer', email: 'blog-editor@test.local', passwordHash: 'x' } });
  editor = { id: u.id, name: u.name };
  env.BLOG_GITHUB_TOKEN = undefined;
});

test('blog rules: HTML, plain http, an H1, too few sections and outside images are all problems', () => {
  const known = new Set<string>();
  const msgs = (md: string) => bodyProblems(md, known).map((x) => x.message).join(' | ');
  assert.match(msgs('## A\n\n<script>alert(1)</script>'), /HTML/);
  assert.match(msgs('## A\n\n<img src=x onerror=alert(1)>'), /HTML/);
  assert.match(msgs('## A\n\nSee http://example.com'), /https/);
  assert.match(msgs('# Title\n\n## A'), /"##"/);
  assert.match(msgs('## Only one'), /at least 2 sections/);
  assert.match(msgs('## A\n\n![x](https://evil.test/a.png)'), /image library/);
  assert.match(msgs('## A\n\n[x](javascript:alert(1))'), /can't be used/);
  // Code is only text: HTML inside it is fine.
  assert.doesNotMatch(msgs('## A\n\n`<div>` and\n\n```\n<b>x</b>\n```\n\n## B'), /HTML/);
  // Autolinks are links, not HTML.
  assert.doesNotMatch(msgs('## A\n\n<https://hostelcare.co.in>\n\n## B'), /HTML/);
});

test('blog rules: slugs, India dates and field limits', () => {
  assert.equal(slugify('  Hostel & PG: Fee Reminders — 2026!  '), 'hostel-and-pg-fee-reminders-2026');
  // 20:00 UTC on 9 Nov is 01:30 on 10 Nov in India.
  assert.equal(istDate(new Date('2026-11-09T20:00:00Z')), '2026-11-10');
  assert.throws(() => p({ metaTitle: 'x'.repeat(61) }), /at most 60/);
  assert.throws(() => p({ description: 'x'.repeat(161) }), /at most 160/);
  assert.throws(() => p({ slug: 'Bad Slug' }), /lowercase/);
  assert.throws(() => p({ status: 'PUBLISHED' }), /Unrecognized key/); // status only through the actions
});

let coverId = '';
let imageId = '';
let postId = '';

test('blog media: type from the bytes, size from the header, private key', async () => {
  await assert.rejects(() => media.createMedia({ body: Buffer.from('GIF89a........'), filename: 'a.gif', userId: editor.id }), /JPG, PNG or WebP/);
  await assert.rejects(() => media.createMedia({ body: png(50, 50), filename: 'tiny.png', userId: editor.id }), /between 100/);
  const cover = await media.createMedia({ body: png(), filename: 'cover.png', alt: 'Cover', userId: editor.id });
  assert.equal(cover.width, 1200);
  assert.equal(cover.height, 800);
  assert.ok(cover.key.startsWith('platform/website-blog/'), 'blog images live outside every tenant prefix');
  assert.ok(stored.has(cover.key));
  coverId = cover.id;
  imageId = (await media.createMedia({ body: png(800, 600), filename: 'inline.png', userId: editor.id })).id;
});

test('blog posts: a draft may be incomplete; the address comes from the title and avoids taken ones', async () => {
  const a = await posts.createPost(p({ title: 'Hostel Fee Reminders That Get Paid' }), editor);
  assert.equal(a.slug, 'hostel-fee-reminders-that-get-paid');
  assert.equal(a.status, BlogPostStatus.DRAFT);
  assert.equal(a.authorName, 'Asha Writer');
  assert.ok(a.problems.length > 0, 'an empty draft lists what it still needs');
  const b = await posts.createPost(p({ title: 'Hostel Fee Reminders That Get Paid' }), editor);
  assert.equal(b.slug, 'hostel-fee-reminders-that-get-paid-2');
  await assert.rejects(() => posts.createPost(p({ title: 'Reserved', slug: 'best-hostel-management-software-india' }), editor), ConflictError);
  onSite.add('a-page-added-by-hand');
  await assert.rejects(() => posts.createPost(p({ title: 'On the site', slug: 'a-page-added-by-hand' }), editor), /already a page on the website/);
  await posts.archivePost(b.id, editor);
  postId = a.id;
});

test('blog publish: refused with the list of problems until ready', async () => {
  await assert.rejects(
    () => posts.publishPost(postId, null, editor),
    (err: unknown) => err instanceof UnprocessableError && (err.details as { problems: unknown[] }).problems.length >= 4,
  );
  await posts.updatePost(postId, await readyFields(coverId, imageId), editor);
  const live = await posts.publishPost(postId, null, editor);
  assert.equal(live.status, BlogPostStatus.PUBLISHED);
  assert.deepEqual(live.problems, []);
  assert.ok(live.slugLocked);
  assert.equal(live.liveUrl, 'https://hostelcare.co.in/resources/blog/hostel-fee-reminders-that-get-paid/');
  // GitHub not set up yet: the build waits, and says why.
  assert.equal(live.build?.state, BlogBuildState.PENDING);
  assert.match(live.build?.lastError ?? '', /BLOG_GITHUB_TOKEN/);
  assert.equal(gh.dispatched, 0);
  assert.equal(live.mediaUrls[coverId], `https://s3.test/platform/website-blog/${coverId}.png?signed`);
});

test('blog live post: a save that would break the site is refused, and nothing changes', async () => {
  const before = await raw.blogPost.findUniqueOrThrow({ where: { id: postId } });
  await assert.rejects(() => posts.updatePost(postId, p({ description: null }), editor), /stay ready to publish/);
  await assert.rejects(() => posts.updatePost(postId, p({ bodyMd: '## One\n\n<iframe src="https://x.test"></iframe>' }), editor), UnprocessableError);
  await assert.rejects(() => posts.updatePost(postId, p({ coverMediaId: null }), editor), UnprocessableError);
  const after = await raw.blogPost.findUniqueOrThrow({ where: { id: postId } });
  assert.equal(after.description, before.description);
  assert.equal(after.bodyMd, before.bodyMd);
  assert.equal(after.coverMediaId, before.coverMediaId);
});

test('blog live post: the address is fixed once it has been on the site, even after unpublishing', async () => {
  await assert.rejects(() => posts.updatePost(postId, p({ slug: 'a-new-address' }), editor), /can no longer change/);
  await posts.unpublishPost(postId, editor);
  await assert.rejects(() => posts.updatePost(postId, p({ slug: 'a-new-address' }), editor), /can no longer change/);
  await posts.publishPost(postId, null, editor);
});

test('blog builds: edits while one build waits share it', async () => {
  const pendingBefore = await raw.blogBuild.count({ where: { state: BlogBuildState.PENDING } });
  const edited = await posts.updatePost(postId, p({ title: 'Hostel Fee Reminders That Actually Get Paid' }), editor);
  assert.ok(edited.contentUpdatedAt, 'an edit while live is dated');
  assert.equal(await raw.blogBuild.count({ where: { state: BlogBuildState.PENDING } }), pendingBefore, 'no second pending build');
  assert.equal(pendingBefore, 1);
});

test('blog builds: sent once GitHub is set up, followed to live; one at a time', async () => {
  env.BLOG_GITHUB_TOKEN = 'test-token';
  await builds.dispatchPending();
  assert.equal(gh.dispatched, 1);
  const sent = await raw.blogBuild.findFirstOrThrow({ where: { state: BlogBuildState.QUEUED } });
  // Another change while that one runs waits as PENDING, not sent.
  await posts.updatePost(postId, p({ authorName: 'Priya Sharma' }), editor);
  assert.equal(gh.dispatched, 1, 'nothing is sent while a build runs');
  gh.runs = [{ id: 501, status: 'in_progress', conclusion: null, html_url: 'https://github.test/runs/501', created_at: new Date().toISOString() }];
  await builds.pollBuilds();
  assert.equal((await raw.blogBuild.findUniqueOrThrow({ where: { id: sent.id } })).state, BlogBuildState.BUILDING);
  gh.runs[0] = { ...gh.runs[0], status: 'completed', conclusion: 'success' };
  await builds.pollBuilds();
  const done = await raw.blogBuild.findUniqueOrThrow({ where: { id: sent.id } });
  assert.equal(done.state, BlogBuildState.LIVE);
  assert.equal(done.runUrl, 'https://github.test/runs/501');
  assert.equal(gh.dispatched, 2, 'the waiting build is sent once the first finished');
});

test('blog builds: "Try again" moves the failed posts to the new build', async () => {
  const open = await raw.blogBuild.findFirstOrThrow({ where: { state: BlogBuildState.QUEUED } });
  await raw.blogBuild.update({ where: { id: open.id }, data: { state: BlogBuildState.FAILED, finishedAt: new Date() } });
  await raw.blogPost.update({ where: { id: postId }, data: { lastBuildId: open.id } });
  const res = await builds.retryBuild(editor.id);
  const post = await raw.blogPost.findUniqueOrThrow({ where: { id: postId } });
  assert.notEqual(post.lastBuildId, open.id);
  assert.equal(post.lastBuildId, res.build?.id);
  // Settle it, so later tests start with no build running.
  await raw.blogBuild.updateMany({ where: { state: { in: [BlogBuildState.PENDING, BlogBuildState.QUEUED, BlogBuildState.BUILDING] } }, data: { state: BlogBuildState.LIVE } });
  env.BLOG_GITHUB_TOKEN = undefined;
});

test('blog media: an image any post uses cannot be deleted, a deleted post included', async () => {
  await assert.rejects(() => media.deleteMedia(coverId), /is used in/);
  const spare = await posts.createPost(p({ title: 'Spare post', bodyMd: `## A\n\n![x](${mediaPath(imageId)})` }), editor);
  await posts.archivePost(spare.id, editor);
  await posts.updatePost(postId, p({ bodyMd: (await readyFields(coverId, imageId)).bodyMd!.replace(/!\[[^\]]*\]\([^)]*\)\n\n/, '') }), editor);
  await assert.rejects(() => media.deleteMedia(imageId), /Spare post/);
  const unused = await media.createMedia({ body: png(), filename: 'unused.png', userId: editor.id });
  assert.deepEqual(await media.deleteMedia(unused.id), { ok: true });
  assert.ok(!stored.has(unused.key), 'the S3 object goes too');
  await raw.blogBuild.updateMany({ where: { state: BlogBuildState.PENDING }, data: { state: BlogBuildState.LIVE } });
});

test('blog schedule: a later time waits, then goes live by itself', async () => {
  const s = await posts.createPost(p({ ...(await readyFields(coverId, imageId)), title: 'Scheduled reminder guide' }), editor);
  const at = new Date(Date.now() + 3 * 3600_000);
  const scheduled = await posts.publishPost(s.id, at, editor);
  assert.equal(scheduled.status, BlogPostStatus.SCHEDULED);
  assert.ok(!(await posts.feed()).posts.some((x) => x.slug === s.slug), 'not in the feed before its time');
  // Saving a scheduled post is checked like a live one.
  await assert.rejects(() => posts.updatePost(s.id, p({ metaTitle: null }), editor), UnprocessableError);
  // Its time comes: the job runs after publishAt has passed.
  await raw.blogPost.update({ where: { id: s.id }, data: { publishAt: new Date(Date.now() - 60_000) } });
  assert.equal(await posts.releaseScheduled(), 1);
  assert.equal(await posts.releaseScheduled(), 0, 'released once only');
  const now = await raw.blogPost.findUniqueOrThrow({ where: { id: s.id } });
  assert.equal(now.status, BlogPostStatus.PUBLISHED);
  assert.ok(now.lastBuildId);
  assert.ok((await posts.feed()).posts.some((x) => x.slug === s.slug));
});

test('blog feed: live posts only, in the website shape, with a link for every image', async () => {
  const f = await posts.feed();
  assert.equal(f.count, f.posts.length);
  assert.ok(f.posts.every((x) => x.cover && x.metaTitle && x.description), 'only complete posts');
  const post = f.posts.find((x) => x.slug === 'hostel-fee-reminders-that-get-paid')!;
  assert.equal(post.title, 'Hostel Fee Reminders That Actually Get Paid');
  assert.equal(post.author, 'Priya Sharma');
  assert.deepEqual(post.cover, { path: mediaPath(coverId), alt: 'An owner sending reminders', width: 1200, height: 800 });
  assert.match(post.date, /^\d{4}-\d{2}-\d{2}$/);
  const paths = new Set(f.media.map((m) => m.path));
  for (const x of f.posts) assert.ok(paths.has(x.cover!.path), 'every cover has a download link');
  assert.ok(f.media.every((m) => m.url.startsWith('https://s3.test/platform/website-blog/')));
  assert.ok(!f.posts.some((x) => x.slug.startsWith('spare-post')), 'deleted posts never appear');
});

test('blog history: restoring an old version keeps the post live, and its rules still apply', async () => {
  const revs = await posts.listRevisions(postId, { page: 1, limit: 50 });
  assert.ok(revs.total >= 5);
  const firstDraft = revs.items[revs.items.length - 1]; // "Created": an empty draft
  assert.equal(firstDraft.note, 'Created');
  await assert.rejects(() => posts.restoreRevision(postId, firstDraft.id, editor), UnprocessableError);
  const published = revs.items.find((r) => r.note === 'Published')!;
  const restored = await posts.restoreRevision(postId, published.id, editor);
  assert.equal(restored.status, BlogPostStatus.PUBLISHED);
  assert.equal(restored.title, 'Hostel Fee Reminders That Get Paid');
  assert.equal(restored.slug, 'hostel-fee-reminders-that-get-paid');
  await raw.blogBuild.updateMany({ where: { state: BlogBuildState.PENDING }, data: { state: BlogBuildState.LIVE } });
});

test('blog Word import: the extractors', () => {
  const seo = extractSeoTable('| Field | Value |\n| --- | --- |\n| SEO title | Fees \\| HostelCare |\n| URL | /blog/x |\n\nBody');
  assert.deepEqual(seo.rows, [['SEO title', 'Fees | HostelCare'], ['URL', '/blog/x']]);
  const faq = extractFaqs('## A\n\ntext\n\n## FAQs\n\n### One?\n\nYes.\n\n### Two?\n\nNo.\n\n## End');
  assert.deepEqual(faq.faqs, [{ q: 'One?', a: 'Yes.' }, { q: 'Two?', a: 'No.' }]);
  assert.ok(faq.md.includes('## End') && !faq.md.includes('One?'));
  const cta = extractCta('## Body\n\nText.\n\n## See it live\n\nBook a free demo today.');
  assert.deepEqual(cta.cta, { heading: 'See it live', text: 'Book a free demo today.' });
});

test('blog Word import: a real .docx becomes a draft with its SEO fields, FAQs, CTA and notes', async () => {
  await assert.rejects(() => importDocx({ body: Buffer.from('not a zip'), filename: 'x.docx' }, editor), BadRequestError);
  const body = readFileSync(join(__dirname, 'fixtures', 'blog-sample.docx'));
  const res = await importDocx({ body, filename: 'blog-sample.docx' }, editor);
  const d = res.post;
  assert.equal(d.status, BlogPostStatus.DRAFT);
  assert.equal(d.title, 'Hostel Fee Reminders That Actually Get Paid');
  assert.equal(d.slug, 'hostel-fee-reminders-guide');
  assert.equal(d.metaTitle, 'Hostel Fee Reminders: A Practical Guide');
  assert.ok(d.description?.startsWith('How hostel owners in India'));
  assert.deepEqual(d.keywords, ['hostel fee reminders', 'rent reminder', 'PG rent collection']);
  assert.equal(d.coverAlt, 'A hostel owner sending fee reminders from a phone');
  assert.equal(d.authorName, 'Priya Sharma');
  assert.equal(d.faqs.length, 2);
  assert.equal(d.cta?.heading, 'Try it in your hostel');
  assert.ok(d.bodyMd.includes('## Why reminders matter') && d.bodyMd.includes('## When to send them'));
  assert.ok(!d.bodyMd.includes('Frequently asked'), 'FAQs leave the body');
  assert.ok(!d.bodyMd.includes('[Add a screenshot'), 'notes leave the body');
  assert.ok(res.importNotes.some((n) => /screenshot/i.test(n)));
  assert.ok(res.importNotes.some((n) => /cover image/i.test(n)));
});

test('blog: drop the throwaway schema', async () => {
  // Only ever the blog test's own schema, by its exact name.
  const schema = new URL(process.env.DATABASE_URL ?? '').searchParams.get('schema');
  if (schema === 'hc_blog_test') await raw.$executeRawUnsafe('DROP SCHEMA IF EXISTS hc_blog_test CASCADE');
  await raw.$disconnect();
});
