import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it, vi } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  InvalidStateError,
  OauthExchangeFailedError,
  TeamAlreadyConnectedError,
} from "../lib/errors.generated";
import type { SlackOauthAccessResult } from "../lib/slackClient";
import { createStateToken } from "../lib/slackState";
import { run } from "./completeSlackWorkspaceInstall";

const ctx: CommandContext = {
  actorId: "user-1",
  permissions: ["slackWorkspaceIntegration"],
};

const baseConnection = {
  id: "swc-1",
  teamId: "T123",
  teamName: "Acme",
  botUserId: "U999",
  status: "ACTIVE" as const,
  installedAt: new Date("2026-01-01T00:00:00.000Z"),
  lastValidatedAt: null,
  revokedAt: null,
  createdAt: new Date("2026-01-01T00:00:00.000Z"),
  updatedAt: null,
};

function okExchange(): SlackOauthAccessResult {
  return {
    ok: true,
    access_token: "xoxb-secret",
    team: { id: "T123", name: "Acme" },
    bot_user_id: "U999",
  };
}

const SIGNING_SECRET = "test-signing-secret";

async function makeInput(overrides: Partial<Parameters<typeof run>[1]> = {}) {
  return {
    state: await createStateToken(
      {
        userId: "user-1",
        redirectUri: "https://app.example.com/cb",
      },
      SIGNING_SECRET,
    ),
    code: "code-1",
    redirectUri: "https://app.example.com/cb",
    clientId: "client-123",
    clientSecret: "secret-123",
    signingSecret: SIGNING_SECRET,
    ...overrides,
  };
}

describe("completeSlackWorkspaceInstall", () => {
  it("stores one ACTIVE SlackWorkspaceIntegration and returns the bot token on first install", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([], [{ ...baseConnection }]);

    const result = await mock.withTx(async (trx) =>
      run(trx, await makeInput(), ctx, {
        exchangeOauthCode: vi.fn(() => Promise.resolve(okExchange())),
      }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.botToken).toBe("xoxb-secret");
    }
    expect(mock.inserts.length).toBe(1);
  });

  it("updates the existing connection and returns the new bot token on re-install", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseConnection }], [{ ...baseConnection }]);

    const result = await mock.withTx(async (trx) =>
      run(trx, await makeInput(), ctx, {
        exchangeOauthCode: vi.fn(() => Promise.resolve(okExchange())),
      }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.botToken).toBe("xoxb-secret");
    }
    expect(mock.updates.length).toBe(1);
    expect(mock.inserts.length).toBe(0);
  });

  it("rejects a garbage state with INVALID_STATE", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    const result = await mock.withTx(async (trx) =>
      run(trx, await makeInput({ state: "tampered-garbage" }), ctx, {
        exchangeOauthCode: vi.fn(() => Promise.resolve(okExchange())),
      }),
    );

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

  it("rejects an expired state with INVALID_STATE", async () => {
    vi.useFakeTimers();
    try {
      vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"));
      const input = await makeInput();
      vi.setSystemTime(new Date("2026-01-01T00:10:01.000Z"));

      const mock = createKyselyMock<Namespace[keyof Namespace]>();
      const result = await mock.withTx((trx) =>
        run(trx, input, ctx, {
          exchangeOauthCode: vi.fn(() => Promise.resolve(okExchange())),
        }),
      );

      expect(result.ok).toBe(false);
      if (!result.ok) {
        expect(result.error).toBeInstanceOf(InvalidStateError);
      }
    } finally {
      vi.useRealTimers();
    }
  });

  it("rejects a state whose userId does not match the calling actor with INVALID_STATE", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    const foreignActorState = await createStateToken(
      {
        userId: "someone-else",
        redirectUri: "https://app.example.com/cb",
      },
      SIGNING_SECRET,
    );

    const result = await mock.withTx(async (trx) =>
      run(trx, await makeInput({ state: foreignActorState }), ctx, {
        exchangeOauthCode: vi.fn(() => Promise.resolve(okExchange())),
      }),
    );

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

  it("rejects a state whose signature does not verify against the supplied signingSecret with INVALID_STATE", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    // State signed with SIGNING_SECRET, but the install is completed with a
    // different signingSecret — the HMAC verification fails.
    const result = await mock.withTx(async (trx) =>
      run(trx, { ...(await makeInput()), signingSecret: "different-secret" }, ctx, {
        exchangeOauthCode: vi.fn(() => Promise.resolve(okExchange())),
      }),
    );

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

  it("rejects a redirectUri that differs from the one pinned in the state with INVALID_STATE", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    const result = await mock.withTx(async (trx) =>
      run(trx, await makeInput({ redirectUri: "https://evil.example.com/cb" }), ctx, {
        exchangeOauthCode: vi.fn(() => Promise.resolve(okExchange())),
      }),
    );

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

  it("rejects when the OAuth exchange returns not-ok with OAUTH_EXCHANGE_FAILED", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    const result = await mock.withTx(async (trx) =>
      run(trx, await makeInput(), ctx, {
        exchangeOauthCode: vi.fn(() => Promise.resolve({ ok: false, error: "invalid_code" })),
      }),
    );

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

  it("rejects a different teamId while an ACTIVE connection exists with TEAM_ALREADY_CONNECTED", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults([{ ...baseConnection, teamId: "T-other" }]);

    const result = await mock.withTx(async (trx) =>
      run(trx, await makeInput(), ctx, {
        exchangeOauthCode: vi.fn(() => Promise.resolve(okExchange())),
      }),
    );

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

  it("reactivates a previously REVOKED connection", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    mock.enqueueResults(
      [{ ...baseConnection, status: "REVOKED", revokedAt: new Date("2026-02-01T00:00:00.000Z") }],
      [{ ...baseConnection, status: "ACTIVE" }],
    );

    const result = await mock.withTx(async (trx) =>
      run(trx, await makeInput(), ctx, {
        exchangeOauthCode: vi.fn(() => Promise.resolve(okExchange())),
      }),
    );

    expect(result.ok).toBe(true);
    expect(mock.updates.length).toBe(1);
    const patch = mock.updates[0].updateValues() as { status?: string; revokedAt?: unknown };
    expect(patch.status).toBe("ACTIVE");
    expect(patch.revokedAt).toBeNull();
  });

  it("deterministically updates the oldest row (orderBy createdAt) when multiple connection rows exist", async () => {
    const mock = createKyselyMock<Namespace[keyof Namespace]>();
    const oldest = {
      ...baseConnection,
      id: "swc-oldest",
      createdAt: new Date("2026-01-01T00:00:00.000Z"),
    };
    mock.enqueueResults([oldest], [{ ...oldest }]);

    const result = await mock.withTx(async (trx) =>
      run(trx, await makeInput(), ctx, {
        exchangeOauthCode: vi.fn(() => Promise.resolve(okExchange())),
      }),
    );

    expect(result.ok).toBe(true);
    const lookupSql = mock.selects[0].sql.toLowerCase();
    expect(lookupSql).toContain('order by "createdat"');
    expect(lookupSql).toContain("limit");
    expect(mock.inserts.length).toBe(0);
    expect(mock.updates.length).toBe(1);
    expect(mock.updates[0].parameters).toContain("swc-oldest");
  });
});
