import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  PartnerNotFoundError,
  PartnerInactiveError,
  MissingRequiredAddressFieldError,
  InvalidCountryCodeError,
} from "../lib/errors.generated";
import {
  baseActivePartner,
  baseDraftPartner,
  baseInactivePartner,
  baseBillingAddress,
} from "../testing/fixtures";
import { run } from "./createPartnerAddress";

describe("createPartnerAddress", () => {
  const validInput = {
    partnerId: "partner-2",
    addressType: "BILLING" as const,
    line1: "123 Main St",
    city: "New York",
    postalCode: "10001",
    country: "US",
  };

  it("creates address for active partner", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const createdAddress = {
      ...baseBillingAddress,
      id: "new-address-id",
    };
    mock.enqueueResults([baseActivePartner], [createdAddress]);

    const result = await mock.withTx((trx) => run(trx, validInput));

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.address.id).toBe("new-address-id");
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

  it("creates address for draft partner", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const createdAddress = {
      ...baseBillingAddress,
      id: "new-address-id",
      partnerId: "partner-1",
    };
    mock.enqueueResults([baseDraftPartner], [createdAddress]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        ...validInput,
        partnerId: "partner-1",
      }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.address).toBeDefined();
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

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

    const result = await mock.withTx((trx) =>
      run(trx, {
        ...validInput,
        partnerId: "nonexistent",
      }),
    );

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

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

    const result = await mock.withTx((trx) =>
      run(trx, {
        ...validInput,
        partnerId: "partner-3",
      }),
    );

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

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

    const result = await mock.withTx((trx) =>
      run(trx, {
        ...validInput,
        line1: "",
      }),
    );

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

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

    const result = await mock.withTx((trx) =>
      run(trx, {
        ...validInput,
        country: "USA",
      }),
    );

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

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

    const result = await mock.withTx((trx) =>
      run(trx, {
        ...validInput,
        country: "us",
      }),
    );

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

  it("creates non-default address", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const createdAddress = {
      ...baseBillingAddress,
      id: "new-address-id",
      isDefault: false,
    };
    mock.enqueueResults([baseActivePartner], [createdAddress]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        ...validInput,
        isDefault: false,
      }),
    );

    expect(result.ok).toBe(true);
    // No update call to unset previous defaults
    expect(mock.updates).toHaveLength(0);
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

  it("unsets previous default when creating with isDefault true", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const createdAddress = {
      ...baseBillingAddress,
      id: "new-address-id",
      isDefault: true,
    };
    mock.enqueueResults([baseActivePartner], [], [createdAddress]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        ...validInput,
        isDefault: true,
      }),
    );

    expect(result.ok).toBe(true);
    // The update call unsets previous defaults
    expect(mock.updates.length).toBeGreaterThan(0);
    expect(mock.inserts.length).toBeGreaterThan(0);
  });
});
