import { describe, it, expect } from "vitest";
import { ZodError } from "zod";
import { signInUseCase, signInOutputSchema } from "@/application/use-cases/sign-in.use-case";
import { MockUsersRepository } from "@/infrastructure/repositories/users.repository.mock";
import { MockAuthenticationService } from "@/infrastructure/services/authentication.service.mock";
import { AuthenticationError } from "@/entities/errors/auth";
import type { IAuthenticationService } from "@/application/services/authentication.service.interface";
import { userFactory } from "@/__factories__/user.factory";

describe("signInUseCase", () => {
  it("returns a session + cookie on valid credentials", async () => {
    const users = new MockUsersRepository([]);
    const auth = new MockAuthenticationService(users);
    const seedUser = userFactory.build({
      username: "alice",
      passwordHash: "hashed_testpassword",
    });
    await users.createUser(seedUser);

    const useCase = signInUseCase(users, auth);
    const result = await useCase({ username: "alice", password: "testpassword" });

    expect(result.session.userId).toBe(seedUser.id);
    expect(result.cookie.name).toBe("session");
  });

  it("throws AuthenticationError when user does not exist", async () => {
    const users = new MockUsersRepository([]);
    const auth = new MockAuthenticationService(users);
    const useCase = signInUseCase(users, auth);

    await expect(
      useCase({ username: "ghost", password: "anything" }),
    ).rejects.toBeInstanceOf(AuthenticationError);
  });

  it("throws AuthenticationError on wrong password", async () => {
    const users = new MockUsersRepository([]);
    const auth = new MockAuthenticationService(users);
    await users.createUser(
      userFactory.build({ username: "alice", passwordHash: "hashed_correctpassword" }),
    );

    const useCase = signInUseCase(users, auth);
    await expect(
      useCase({ username: "alice", password: "wrong" }),
    ).rejects.toBeInstanceOf(AuthenticationError);
  });
});

describe("signInUseCase output validation (R25)", () => {
  it("throws when authenticationService returns a malformed session", async () => {
    const users = new MockUsersRepository([]);
    const seed = userFactory.build({ username: "alice" });
    await users.createUser(seed);

    const auth = {
      verifyPassword: async () => true,
      // session missing required fields → should fail signInOutputSchema.parse
      createSession: async () => ({ session: { id: 123 }, cookie: null }),
    } as unknown as IAuthenticationService;

    const useCase = signInUseCase(users, auth);
    await expect(useCase({ username: "alice", password: "x" })).rejects.toBeInstanceOf(ZodError);
  });

  it("exports an output schema that mirrors the success shape", () => {
    expect(signInOutputSchema).toBeDefined();
    const parsed = signInOutputSchema.safeParse({
      session: { id: "s1", userId: "u1", expiresAt: new Date() },
      cookie: { name: "session", value: "s1", attributes: {} },
    });
    expect(parsed.success).toBe(true);
  });
});
