import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  PartnerNotFoundError,
  PartnerNotOrganizationError,
  InvalidFirstNameError,
  InvalidLastNameError,
  MissingCommunicationChannelError,
  InvalidEmailFormatError,
} from "../lib/errors.generated";
import { baseActivePartner, baseIndividualPartner } from "../testing/fixtures";
import { run } from "./createContactPerson";

describe("createContactPerson", () => {
  it("creates contact person", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseActivePartner],
      [
        {
          id: "new-contact",
          partnerId: baseActivePartner.id,
          firstName: "Jane",
          lastName: "Doe",
          email: "jane@example.com",
          phone: null,
          jobTitle: null,
          department: null,
          isPrimary: false,
          status: "ACTIVE",
        },
      ],
    );

    const result = await mock.withTx((trx) =>
      run(trx, {
        partnerId: baseActivePartner.id,
        firstName: "Jane",
        lastName: "Doe",
        email: "jane@example.com",
      }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.contact.status).toBe("ACTIVE");
      expect(result.value.contact.isPrimary).toBe(false);
    }
  });

  it("returns error when partner not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        partnerId: "nonexistent",
        firstName: "Jane",
        lastName: "Doe",
        email: "jane@example.com",
      }),
    );

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

  it("returns error when partner is INDIVIDUAL", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseIndividualPartner]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        partnerId: baseIndividualPartner.id,
        firstName: "Jane",
        lastName: "Doe",
        email: "jane@example.com",
      }),
    );

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

  it("returns error when firstName is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActivePartner]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        partnerId: baseActivePartner.id,
        firstName: "",
        lastName: "Doe",
        email: "jane@example.com",
      }),
    );

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

  it("returns error when lastName is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActivePartner]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        partnerId: baseActivePartner.id,
        firstName: "Jane",
        lastName: "",
        email: "jane@example.com",
      }),
    );

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

  it("returns error when neither email nor phone provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActivePartner]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        partnerId: baseActivePartner.id,
        firstName: "Jane",
        lastName: "Doe",
      }),
    );

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

  it("returns error when whitespace-only channels provided as only communication", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActivePartner]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        partnerId: baseActivePartner.id,
        firstName: "Jane",
        lastName: "Doe",
        email: "   ",
        phone: "   ",
      }),
    );

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

  it("returns error for invalid email format", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActivePartner]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        partnerId: baseActivePartner.id,
        firstName: "Jane",
        lastName: "Doe",
        email: "invalid-email",
      }),
    );

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

  it("creates with ACTIVE status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseActivePartner],
      [
        {
          id: "new-contact",
          partnerId: baseActivePartner.id,
          firstName: "Jane",
          lastName: "Doe",
          email: "jane@example.com",
          phone: null,
          jobTitle: null,
          department: null,
          isPrimary: false,
          status: "ACTIVE",
        },
      ],
    );

    const result = await mock.withTx((trx) =>
      run(trx, {
        partnerId: baseActivePartner.id,
        firstName: "Jane",
        lastName: "Doe",
        email: "jane@example.com",
      }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.contact.status).toBe("ACTIVE");
    }
  });
});
