import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  MissingRequiredFieldError,
  TemplateNotFoundError,
  UndeclaredVariableReferenceError,
} from "../lib/errors.generated";
import { baseTemplate, baseEmailTemplate } from "../testing/fixtures";
import { run } from "./updateNotificationTemplate";

describe("updateNotificationTemplate", () => {
  const ctx: CommandContext = { actorId: "buyer-1", permissions: [] };

  it("updates the subject on an existing NotificationTemplate row", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseTemplate }]);

    const result = await mock.withTx((trx) =>
      run(trx, { templateId: "template-1", subject: "PO {{poNumber}} updated" }, ctx),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.template.subject).toBe("PO {{poNumber}} updated");
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("updates body and htmlBody together in one call", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseEmailTemplate }]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          templateId: "template-2",
          body: "New body {{poNumber}}.",
          htmlBody: "<p>New {{poNumber}}.</p>",
        },
        ctx,
      ),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.template.body).toBe("New body {{poNumber}}.");
      expect(result.value.template.htmlBody).toBe("<p>New {{poNumber}}.</p>");
    }
  });

  it("updates the variableSchema and persists the new declared variables", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([
      {
        ...baseTemplate,
        subject: "Hello {{recipientName}}",
        body: "Hi {{recipientName}}, your PO {{poNumber}} is ready.",
      },
    ]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          templateId: "template-1",
          variableSchema:
            '{"variables":[{"name":"poNumber","required":true,"type":"string"},{"name":"recipientName","required":true,"type":"string"}]}',
        },
        ctx,
      ),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.template.variableSchema).toContain("recipientName");
    }
  });

  it("returns TEMPLATE_NOT_FOUND when the row does not exist", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(trx, { templateId: "missing", subject: "Test" }, ctx),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(TemplateNotFoundError);
    }
  });

  it("returns UNDECLARED_VARIABLE_REFERENCE when the new body references a variable removed from variableSchema in the same update", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseTemplate }]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          templateId: "template-1",
          body: "Hello {{recipientName}}",
          variableSchema: '{"variables":[{"name":"poNumber","required":true,"type":"string"}]}',
        },
        ctx,
      ),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(UndeclaredVariableReferenceError);
    }
  });

  it("returns MISSING_REQUIRED_FIELD when no mutable field is supplied", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseTemplate }]);

    const result = await mock.withTx((trx) => run(trx, { templateId: "template-1" }, ctx));

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(MissingRequiredFieldError);
    }
  });

  it("returns MISSING_REQUIRED_FIELD when supplied subject is blank", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseTemplate }]);

    const result = await mock.withTx((trx) =>
      run(trx, { templateId: "template-1", subject: "   " }, ctx),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(MissingRequiredFieldError);
    }
  });

  it("subsequent renders pick up the new content immediately", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseTemplate }]);

    const result = await mock.withTx((trx) =>
      run(trx, { templateId: "template-1", subject: "Updated {{poNumber}}" }, ctx),
    );

    expect(result.ok).toBe(true);
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("previously persisted Notifications retain their original rendered content", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseTemplate }]);

    const result = await mock.withTx((trx) =>
      run(trx, { templateId: "template-1", body: "Updated body {{poNumber}}" }, ctx),
    );

    // The update only touches NotificationTemplate; existing Notifications are unaffected.
    expect(result.ok).toBe(true);
    expect(mock.updates.length).toBeGreaterThan(0);
    // No write to the Notification table happens.
  });
});
