import { createClient } from "@supabase/supabase-js";
import { describe, expect, it } from "vitest";
import { createConfig } from "../../config.js";
import { MiddlewareManager } from "../../middlewares/middleware.js";
import { getMainRouter } from "../../routers/index.js";
import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js";
import { getTestData } from "../helpers/dbSetup.js";

const ADMIN_TOKEN_SIGNING_SECRET = "admin-test-secret";
const ADMIN_TOKEN_AUDIENCE = "xtablo-admin";

describe("Admin Table Edit Router", () => {
  process.env.ADMIN_TOKEN_SIGNING_SECRET = ADMIN_TOKEN_SIGNING_SECRET;
  process.env.ADMIN_TOKEN_AUDIENCE = ADMIN_TOKEN_AUDIENCE;
  process.env.ADMIN_APP_URL = "http://localhost:5176";

  const config = createConfig();
  MiddlewareManager.initialize(config);
  const app = getMainRouter(config);

  const sessionToken = createSignedAdminToken(
    {
      aud: ADMIN_TOKEN_AUDIENCE,
      email: "ops@xtablo.com",
      exp: Math.floor(Date.now() / 1000) + 900,
      role: "operator",
      sub: "operator-1",
      type: "admin_session",
    },
    ADMIN_TOKEN_SIGNING_SECRET
  );

  it("writes an audit log entry for a successful update", async () => {
    const ownerUserId = getTestData().users.owner.userId;

    const res = await app.request(`/admin/tables/profiles/rows/${ownerUserId}`, {
      method: "PATCH",
      headers: {
        Authorization: `Bearer ${sessionToken}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ first_name: "Ada" }),
    });

    expect(res.status).toBe(200);
    await expect(res.json()).resolves.toMatchObject({
      row: expect.objectContaining({
        first_name: "Ada",
        id: ownerUserId,
      }),
    });

    const auditClient = createClient(config.SUPABASE_URL, config.SUPABASE_SERVICE_ROLE_KEY, {
      auth: { autoRefreshToken: false, persistSession: false },
    });

    const { data: auditRows, error } = await auditClient
      .from("admin_audit_log")
      .select("*")
      .eq("target_id", ownerUserId)
      .eq("action", "update")
      .order("created_at", { ascending: false })
      .limit(1);

    expect(error).toBeNull();
    expect(auditRows).toHaveLength(1);
    expect(auditRows?.[0]).toMatchObject({
      operator_email: "ops@xtablo.com",
      target_type: "profiles",
    });
  });
});
