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

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

describe("searchAuditEntries", () => {
  it("returns entries filtered by actorId", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseAuditEntry]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
      expect(result.value.items[0]).toEqual(baseAuditEntry);
    }
  });

  it("returns entries filtered by actorType and actorId", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseAuditEntry]);

    const result = await run(db, { actorType: "USER", actorId: "user-1" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
    }
  });

  it("returns entries filtered by entityType", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseAuditEntry]);

    const result = await run(db, { entityType: "SalesOrder" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
    }
  });

  it("returns entries filtered by entityType and entityId", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseAuditEntry]);

    const result = await run(db, { entityType: "SalesOrder", entityId: "so-1" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
    }
  });

  it("returns entries filtered by operationType", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseAuditEntry]);

    const result = await run(db, { operationType: "UPDATE" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
    }
  });

  it("returns entries filtered by date range", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseAuditEntry]);

    const result = await run(
      db,
      {
        dateFrom: new Date("2024-01-01"),
        dateTo: new Date("2024-12-31"),
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
    }
  });

  it("returns entries filtered by companyId", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseAuditEntry]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
      expect(result.value.items[0].companyId).toBe("company-1");
    }
  });

  it("returns global entries when companyId is omitted", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([globalAuditEntry]);

    const result = await run(db, { entityType: "User" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
      expect(result.value.items[0].companyId).toBeNull();
    }
  });

  it("returns only company entries when scope is COMPANY", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseAuditEntry]);

    const result = await run(db, { scope: "COMPANY", companyId: "company-1" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
      expect(result.value.items[0].companyId).toBe("company-1");
    }
  });

  it("returns only global entries when scope is GLOBAL", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([globalAuditEntry]);

    const result = await run(db, { scope: "GLOBAL" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
      expect(result.value.items[0].companyId).toBeNull();
    }
  });

  it("returns combined company and global entries when scope is ALL", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseAuditEntry, globalAuditEntry]);

    const result = await run(db, { scope: "ALL" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(2);
    }
  });

  it("restricts combined results to scopes the caller is authorized for when scope is ALL", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseAuditEntry, globalAuditEntry]);

    const result = await run(db, { scope: "ALL" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(2);
    }
  });

  it("returns only company entries in combined scope when caller lacks global permission", async () => {
    // Permission enforcement is middleware; query layer returns what DB gives
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseAuditEntry]);

    const result = await run(db, { scope: "ALL" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
    }
  });

  it("returns only global entries in combined scope when caller lacks company permission", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([globalAuditEntry]);

    const result = await run(db, { scope: "ALL" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
    }
  });

  it("filters combined scope results by companyId when both scope=ALL and companyId are provided", async () => {
    const { db, spies } = createMockDb<DB>();
    // scope=ALL + companyId returns company entries + global entries (combined)
    spies.select.mockReturnValue([baseAuditEntry, globalAuditEntry]);

    const result = await run(db, { scope: "ALL", companyId: "company-1" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(2);
    }
  });

  it("rejects scope=COMPANY when companyId is not provided", async () => {
    const { db } = createMockDb<DB>();

    const result = await run(db, { scope: "COMPANY" }, ctx);

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

  it("rejects invalid scope value", async () => {
    const { db } = createMockDb<DB>();

    const result = await run(db, { scope: "INVALID", entityType: "SalesOrder" }, ctx);

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

  it("returns entries filtered by correlationId", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([globalAuditEntry]);

    const result = await run(db, { correlationId: "corr-uuid-1" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
      expect(result.value.items[0].correlationId).toBe("corr-uuid-1");
    }
  });

  it("combines multiple filter criteria", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseAuditEntry]);

    const result = await run(
      db,
      {
        actorId: "user-1",
        entityType: "SalesOrder",
        operationType: "UPDATE",
        companyId: "company-1",
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
    }
  });

  it("returns results in chronological order", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseAuditEntry, globalAuditEntry]);

    const result = await run(db, { scope: "ALL" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(2);
      // Default order is timestamp asc
      expect(result.value.items[0].timestamp.getTime()).toBeLessThanOrEqual(
        result.value.items[1].timestamp.getTime(),
      );
    }
  });

  it("paginates large result sets", async () => {
    const { db, spies } = createMockDb<DB>();
    const manyEntries = Array.from({ length: 3 }, (_, i) => ({
      ...baseAuditEntry,
      id: `entry-${i}`,
    }));
    spies.select.mockReturnValue(manyEntries);

    const result = await run(db, { entityType: "SalesOrder", limit: 2 }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(2);
      expect(result.value.hasNextPage).toBe(true);
    }
  });

  it("returns empty list when no entries match", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([]);

    const result = await run(db, { entityType: "NonExistent" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(0);
      expect(result.value.hasNextPage).toBe(false);
    }
  });

  it("rejects when no filter parameters are provided", async () => {
    const { db } = createMockDb<DB>();

    const result = await run(db, {}, ctx);

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

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

    const result = await run(db, { entityType: "SalesOrder" }, noPermsCtx);

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

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

    const result = await run(db, { companyId: "company-2" }, scopedCtx);

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

  it("restricts company-scoped caller to their company even when scope=GLOBAL", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([]);
    const scopedCtx: QueryContext = {
      actorId: "test-actor",
      permissions: ["audit:viewAuditHistory"],
      companyId: "company-1",
    };

    const result = await run(db, { scope: "GLOBAL" }, scopedCtx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(0);
    }
  });

  it("restricts company-scoped caller to their company even when scope=ALL", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([baseAuditEntry]);
    const scopedCtx: QueryContext = {
      actorId: "test-actor",
      permissions: ["audit:viewAuditHistory"],
      companyId: "company-1",
    };

    const result = await run(db, { scope: "ALL" }, scopedCtx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
      expect(result.value.items[0].companyId).toBe("company-1");
    }
  });

  it("restricts global-scoped caller to global entries even when scope=COMPANY", async () => {
    const { db } = createMockDb<DB>();
    const globalCtx: QueryContext = {
      actorId: "test-actor",
      permissions: ["audit:viewAuditHistory"],
      companyId: null,
    };

    const result = await run(db, { scope: "COMPANY", companyId: "company-1" }, globalCtx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(0);
    }
  });

  it("restricts global-scoped caller to global entries even when scope=ALL", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValue([globalAuditEntry]);
    const globalCtx: QueryContext = {
      actorId: "test-actor",
      permissions: ["audit:viewAuditHistory"],
      companyId: null,
    };

    const result = await run(db, { scope: "ALL" }, globalCtx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(1);
      expect(result.value.items[0].companyId).toBeNull();
    }
  });
});
