import { describe, expect, it } from "vitest";
import { createActor, waitFor } from "xstate";

import { createTestAuthMachine } from "./auth-machine.test-utils";

describe("auth OAuth flow", () => {
  it("applies Google backend sync status", async () => {
    const actor = createActor(createTestAuthMachine()).start();
    actor.send({ type: "AuthGoogleSyncSubmitted", idToken: "google-token" });
    await waitFor(actor, (snapshot) => snapshot.matches("idle"));
    expect(actor.getSnapshot().context.loginStatus).toBe("google");
    actor.stop();
  });

  it("applies Facebook backend sync status", async () => {
    const actor = createActor(createTestAuthMachine()).start();
    actor.send({
      type: "AuthFacebookSyncSubmitted",
      accessToken: "facebook-token",
    });
    await waitFor(actor, (snapshot) => snapshot.matches("idle"));
    expect(actor.getSnapshot().context.loginStatus).toBe("facebook");
    actor.stop();
  });

  it("returns to idle with an error when OAuth launch fails", async () => {
    const actor = createActor(
      createTestAuthMachine({ oauthSignInError: new Error("oauth failed") }),
    ).start();
    actor.send({ type: "AuthGoogleLoginSubmitted", provider: "google" });
    await waitFor(actor, (snapshot) => snapshot.matches("idle"));
    expect(actor.getSnapshot().context.errorMessage).toBe("oauth failed");
    actor.stop();
  });
});
