import { beforeEach, describe, expect, it, vi } from "vitest";
import { GET, PUT } from "./route";
import { ApiV1Error } from "@/lib/api-v1/errors";

const mocks = vi.hoisted(() => ({
  requireApiV1Auth: vi.fn(),
  getCompanyProfile: vi.fn(),
  updateCompanyProfile: vi.fn(),
}));

vi.mock("@/lib/api-v1/auth", () => ({
  requireApiV1Auth: mocks.requireApiV1Auth,
}));

vi.mock("@/lib/api-v1/services/company-service", () => ({
  getCompanyProfile: mocks.getCompanyProfile,
  updateCompanyProfile: mocks.updateCompanyProfile,
}));

describe("Company API v1", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("retorna perfil da empresa no envelope padrao", async () => {
    mocks.requireApiV1Auth.mockResolvedValue({
      supabase: {},
      user: { id: "user-1" },
    });
    mocks.getCompanyProfile.mockResolvedValue({
      data: {
        id: "company-1",
        name: "Loja Exemplo",
      },
    });

    const response = await GET(new Request("http://localhost/api/v1/company"));
    expect(response.status).toBe(200);
    await expect(response.json()).resolves.toMatchObject({
      success: true,
      data: {
        id: "company-1",
        name: "Loja Exemplo",
      },
    });
  });

  it("nega acesso sem token", async () => {
    mocks.requireApiV1Auth.mockRejectedValue(new ApiV1Error(401, "missing_bearer_token", "Token Bearer obrigatorio."));

    const response = await GET(new Request("http://localhost/api/v1/company"));
    expect(response.status).toBe(401);
    await expect(response.json()).resolves.toMatchObject({
      success: false,
      error: {
        code: "missing_bearer_token",
      },
    });
  });

  it("atualiza perfil da empresa com envelope padrao", async () => {
    mocks.requireApiV1Auth.mockResolvedValue({
      supabase: {},
      user: { id: "user-1" },
    });
    mocks.updateCompanyProfile.mockResolvedValue({
      data: {
        id: "company-1",
        store_name: "Loja Atualizada",
      },
    });

    const response = await PUT(
      new Request("http://localhost/api/v1/company", {
        method: "PUT",
        body: JSON.stringify({ store_name: "Loja Atualizada" }),
      })
    );

    expect(response.status).toBe(200);
    await expect(response.json()).resolves.toMatchObject({
      success: true,
      data: {
        id: "company-1",
        store_name: "Loja Atualizada",
      },
    });
  });
});
