import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  PartnerNotFoundError,
  PartnerInactiveError,
  InvalidAddressTypeError,
  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 { db, spies } = createMockDb<Transaction>();
    const createdAddress = {
      ...baseBillingAddress,
      id: "new-address-id",
    };

    spies.select.mockReturnValueOnce(baseActivePartner); // Partner lookup
    spies.insert.mockReturnValue(createdAddress);

    const result = await run(db, validInput);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.address.id).toBe("new-address-id");
    }
    expect(spies.insert).toHaveBeenCalled();
  });

  it("creates address for draft partner", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const createdAddress = {
      ...baseBillingAddress,
      id: "new-address-id",
      partnerId: "partner-1",
    };

    spies.select.mockReturnValueOnce(baseDraftPartner); // Partner lookup
    spies.insert.mockReturnValue(createdAddress);

    const result = await run(db, { ...validInput, partnerId: "partner-1" });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.address).toBeDefined();
    }
    expect(spies.insert).toHaveBeenCalled();
  });

  it("returns error when partner not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined); // Partner not found

    const result = await run(db, { ...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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseInactivePartner); // Inactive partner

    const result = await run(db, { ...validInput, partnerId: "partner-3" });

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

  it("returns error when address type is invalid", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActivePartner);

    const result = await run(db, {
      ...validInput,
      addressType: "INVALID" as never,
    });

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

  it("returns error when required fields missing", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActivePartner);

    const result = await run(db, {
      ...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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActivePartner);

    const result = await run(db, {
      ...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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActivePartner);

    const result = await run(db, {
      ...validInput,
      country: "us",
    });

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

  it("creates non-default address", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const createdAddress = {
      ...baseBillingAddress,
      id: "new-address-id",
      isDefault: false,
    };

    spies.select.mockReturnValueOnce(baseActivePartner);
    spies.insert.mockReturnValue(createdAddress);

    const result = await run(db, {
      ...validInput,
      isDefault: false,
    });

    expect(result.ok).toBe(true);
    // No update call to unset previous defaults
    expect(spies.update).not.toHaveBeenCalled();
    expect(spies.insert).toHaveBeenCalled();
  });

  it("unsets previous default when creating with isDefault true", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const createdAddress = {
      ...baseBillingAddress,
      id: "new-address-id",
      isDefault: true,
    };

    spies.select.mockReturnValueOnce(baseActivePartner); // Partner lookup
    spies.insert.mockReturnValue(createdAddress);

    const result = await run(db, {
      ...validInput,
      isDefault: true,
    });

    expect(result.ok).toBe(true);
    // The update call unsets previous defaults
    expect(spies.update).toHaveBeenCalled();
    expect(spies.insert).toHaveBeenCalled();
  });
});
