import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { AuditEntryNotFoundError, UnauthorizedError } from "../lib/errors.generated";
import {
  baseAuditEntry,
  globalAuditEntry,
  baseChangeDetail,
  maskedChangeDetail,
  excludedChangeDetail,
  createChangeDetail,
} from "../testing/fixtures";
import { run } from "./getChangeDetails";
import { InsufficientPermissionError } from "@tailor-platform/erp-kit/module";
import type { QueryContext } from "@tailor-platform/erp-kit/module";

const ctx: QueryContext = {
  actorId: "test-actor",
  permissions: ["audit:viewAuditHistory"],
};

describe("getChangeDetails", () => {
  it("returns all change details for an audit entry", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseAuditEntry);
    spies.select.mockReturnValueOnce([baseChangeDetail, maskedChangeDetail]);

    const result = await run(db, { auditEntryId: "entry-1" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.changeDetails).toEqual([baseChangeDetail, maskedChangeDetail]);
      expect(result.value.changeDetails).toHaveLength(2);
    }
  });

  it("returns empty list when audit entry has no change details", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseAuditEntry);
    spies.select.mockReturnValueOnce([]);

    const result = await run(db, { auditEntryId: "entry-1" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.changeDetails).toEqual([]);
    }
  });

  it("returns change details with masked values for MASK sensitivity mode", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseAuditEntry);
    spies.select.mockReturnValueOnce([maskedChangeDetail]);

    const result = await run(db, { auditEntryId: "entry-1" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      const detail = result.value.changeDetails[0];
      expect(detail.oldValue).toBe("***");
      expect(detail.newValue).toBe("***");
    }
  });

  it("returns change details with hashed values for HASH sensitivity mode", async () => {
    const hashedDetail = {
      id: "detail-hash",
      auditEntryId: "entry-1",
      fieldName: "status",
      oldValue: "sha256:abc123",
      newValue: "sha256:def456",
      createdAt: new Date("2024-01-15T10:30:00.000Z"),
      updatedAt: null,
    };
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseAuditEntry);
    spies.select.mockReturnValueOnce([hashedDetail]);

    const result = await run(db, { auditEntryId: "entry-1" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      const detail = result.value.changeDetails[0];
      expect(detail.oldValue).toBe("sha256:abc123");
      expect(detail.newValue).toBe("sha256:def456");
    }
  });

  it("returns change details with null values for EXCLUDE sensitivity mode", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseAuditEntry);
    spies.select.mockReturnValueOnce([excludedChangeDetail]);

    const result = await run(db, { auditEntryId: "entry-1" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      const detail = result.value.changeDetails[0];
      expect(detail.oldValue).toBeNull();
      expect(detail.newValue).toBeNull();
    }
  });

  it("returns change details with raw values for CAPTURE sensitivity mode", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseAuditEntry);
    spies.select.mockReturnValueOnce([baseChangeDetail]);

    const result = await run(db, { auditEntryId: "entry-1" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      const detail = result.value.changeDetails[0];
      expect(detail.oldValue).toBe("100.00");
      expect(detail.newValue).toBe("95.00");
    }
  });

  it("returns change details for company-scoped entry when caller has matching company permission", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseAuditEntry);
    spies.select.mockReturnValueOnce([baseChangeDetail]);
    const companyScopedCtx: QueryContext = {
      actorId: "test-actor",
      permissions: ["audit:viewAuditHistory"],
      companyId: "company-1",
    };

    const result = await run(db, { auditEntryId: baseAuditEntry.id }, companyScopedCtx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.changeDetails).toEqual([baseChangeDetail]);
    }
  });

  it("returns change details for global entry when caller has global-scoped permission", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(globalAuditEntry);
    spies.select.mockReturnValueOnce([createChangeDetail]);
    const globalScopedCtx: QueryContext = {
      actorId: "test-actor",
      permissions: ["audit:viewAuditHistory"],
      companyId: null,
    };

    const result = await run(db, { auditEntryId: globalAuditEntry.id }, globalScopedCtx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.changeDetails).toEqual([createChangeDetail]);
    }
  });

  it("returns error when audit entry does not exist", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { auditEntryId: "nonexistent" }, ctx);

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

  it("rejects when caller lacks permission for entry's company scope", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseAuditEntry); // companyId: "company-1"
    const scopedCtx: QueryContext = {
      actorId: "test-actor",
      permissions: ["audit:viewAuditHistory"],
      companyId: "company-2",
    };

    const result = await run(db, { auditEntryId: baseAuditEntry.id }, scopedCtx);

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

  it("rejects when caller lacks viewAuditHistory permission", async () => {
    const { db } = createMockDb<DB>();
    const noPermsCtx: QueryContext = { actorId: "test-actor", permissions: [] };

    const result = await run(db, { auditEntryId: "entry-1" }, noPermsCtx);

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