import { mkdirSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
	_resetNotificationStore,
	appendNotification,
	initNotificationStore,
	NOTICE_KIND,
	NOTIFICATION_SCHEMA_VERSION_WRITE,
	readNotifications,
} from "../notification-store.js";

describe("notification-store long-term grouping (schema v2)", () => {
	let testDir;

	beforeEach(() => {
		_resetNotificationStore();
		testDir = join(tmpdir(), `sf-notif-group-${Date.now()}`);
		mkdirSync(testDir, { recursive: true });
		initNotificationStore(testDir);
	});

	afterEach(() => {
		try {
			rmSync(testDir, { recursive: true });
		} catch {
			/* ignore */
		}
		_resetNotificationStore();
	});

	it("merges_duplicate_warnings_with_same_dedupe_key_into_one_row_with_repeatCount", () => {
		appendNotification("quota edge", "warning", "notify", {
			dedupe_key: "quota-roll",
		});
		appendNotification("quota edge", "warning", "notify", {
			dedupe_key: "quota-roll",
		});

		const lines = readFileSync(
			join(testDir, ".sf", "notifications.jsonl"),
			"utf-8",
		)
			.trim()
			.split("\n")
			.filter(Boolean);
		expect(lines.length).toBe(1);
		const row = JSON.parse(lines[0]);
		expect(row.schemaVersion).toBe(NOTIFICATION_SCHEMA_VERSION_WRITE);
		expect(row.repeatCount).toBe(2);
		expect(row.lastTs).toBeDefined();

		const [latest] = readNotifications(testDir);
		expect(latest.repeatCount).toBe(2);
	});

	it("does_not_merge_when_merge_is_false", () => {
		appendNotification("unique audit", "warning", "notify", {
			dedupe_key: "audit-x",
			merge: false,
		});
		appendNotification("unique audit", "warning", "notify", {
			dedupe_key: "audit-x",
			merge: false,
		});

		const lines = readFileSync(
			join(testDir, ".sf", "notifications.jsonl"),
			"utf-8",
		)
			.trim()
			.split("\n")
			.filter(Boolean);
		expect(lines.length).toBe(2);
	});

	it("does_not_merge_approval_request_kind_distinct_consent_rows", () => {
		appendNotification("approve deploy?", "warning", "notify", {
			kind: "approval_request",
			dedupe_key: "deploy-approve",
		});
		appendNotification("approve deploy?", "warning", "notify", {
			kind: "approval_request",
			dedupe_key: "deploy-approve",
		});

		const lines = readFileSync(
			join(testDir, ".sf", "notifications.jsonl"),
			"utf-8",
		)
			.trim()
			.split("\n")
			.filter(Boolean);
		expect(lines.length).toBe(2);
	});

	it("persists_noticeKind_on_new_rows", () => {
		appendNotification("SM offline", "warning", "notify", {
			dedupe_key: "sm-health",
			noticeKind: NOTICE_KIND.SYSTEM_NOTICE,
		});
		const [e] = readNotifications(testDir);
		expect(e.noticeKind).toBe(NOTICE_KIND.SYSTEM_NOTICE);
	});
});
