/**
 * /admin/time-tracking/audit
 *
 * Phase 2 — read-only audit trail viewer for admins. Shows every
 * mutating action on a timesheet, its entries, or the related
 * entities, ordered most-recent-first.
 */
import { redirect } from "next/navigation";
import { getAdminUser } from "@/lib/admin-permissions";
import { withBrand } from "@/db/client";
import { timeTrackingAuditLog } from "@/db/schema/time-tracking";
import { PageHeader } from "@/components/admin/design-system";
import { desc, eq, sql } from "drizzle-orm";

const TUXEDO_BRAND_ID = "64294306-5f42-463d-a5e8-2ad6c81a96de";

export const dynamic = "force-dynamic";

export default async function AuditPage({
  searchParams,
}: {
  searchParams: Promise<{ action?: string; entity?: string }>;
}) {
  const adminUser = await getAdminUser();
  if (!adminUser) redirect("/login");
  if (adminUser.role !== "platform_admin" && adminUser.role !== "brand_admin") {
    redirect("/admin/time-tracking");
  }
  const brandId = adminUser.brand_id ?? TUXEDO_BRAND_ID;
  const sp = await searchParams;

  const rows = await withBrand(brandId, async (db) => {
    const conds = [eq(timeTrackingAuditLog.brandId, brandId)];
    if (sp.action) conds.push(eq(timeTrackingAuditLog.action, sp.action));
    if (sp.entity) conds.push(eq(timeTrackingAuditLog.entityType, sp.entity));
    return db
      .select({
        id: timeTrackingAuditLog.id,
        actor_label: timeTrackingAuditLog.actorLabel,
        actor_kind: timeTrackingAuditLog.actorKind,
        action: timeTrackingAuditLog.action,
        entity_type: timeTrackingAuditLog.entityType,
        entity_id: timeTrackingAuditLog.entityId,
        details: timeTrackingAuditLog.details,
        created_at: timeTrackingAuditLog.createdAt,
      })
      .from(timeTrackingAuditLog)
      .where(sql`1=1`)
      .orderBy(desc(timeTrackingAuditLog.createdAt))
      .limit(500);
  });

  return (
    <div className="min-h-screen bg-[var(--admin-bg)]">
      <PageHeader
        title="Audit trail"
        subtitle={`Last ${rows.length} events`}
        className="px-6 pt-6"
      />
      <div className="px-6 pb-8">
        <form className="mb-4 flex flex-wrap items-end gap-3 rounded-2xl border border-zinc-200 bg-white p-4">
          <label className="flex flex-col gap-1">
            <span className="text-[11px] font-bold uppercase tracking-wider text-zinc-500">
              Action
            </span>
            <input
              name="action"
              defaultValue={sp.action ?? ""}
              placeholder="e.g. timesheet.approve"
              className="rounded-md border border-zinc-300 px-3 py-2 text-sm"
            />
          </label>
          <label className="flex flex-col gap-1">
            <span className="text-[11px] font-bold uppercase tracking-wider text-zinc-500">
              Entity type
            </span>
            <select
              name="entity"
              defaultValue={sp.entity ?? ""}
              className="rounded-md border border-zinc-300 bg-white px-3 py-2 text-sm"
            >
              <option value="">All</option>
              <option value="timesheet">timesheet</option>
              <option value="log">log</option>
              <option value="worker">worker</option>
            </select>
          </label>
          <button
            type="submit"
            className="rounded-md bg-zinc-900 px-4 py-2 text-sm font-medium text-white"
          >
            Filter
          </button>
        </form>

        <div className="overflow-hidden rounded-2xl border border-zinc-200 bg-white">
          <table className="w-full text-sm">
            <thead className="border-b border-zinc-200 bg-zinc-50 text-left text-[11px] font-bold uppercase tracking-wider text-zinc-500">
              <tr>
                <th className="px-4 py-3">When</th>
                <th className="px-4 py-3">Action</th>
                <th className="px-4 py-3">Actor</th>
                <th className="px-4 py-3">Entity</th>
                <th className="px-4 py-3">Details</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-zinc-100">
              {rows.map((r) => (
                <tr key={r.id}>
                  <td className="px-4 py-3 whitespace-nowrap text-xs text-zinc-500">
                    {new Date(r.created_at).toLocaleString("en-US", {
                      month: "short",
                      day: "numeric",
                      hour: "numeric",
                      minute: "2-digit",
                    })}
                  </td>
                  <td className="px-4 py-3">
                    <span className="font-mono text-[11px] uppercase tracking-wider text-zinc-700">
                      {r.action}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-zinc-900">
                    {r.actor_label}
                    <span className="ml-1 text-xs text-zinc-500">
                      ({r.actor_kind})
                    </span>
                  </td>
                  <td className="px-4 py-3 text-xs text-zinc-500">
                    {r.entity_type}
                    {r.entity_id && (
                      <span className="ml-1 font-mono">{r.entity_id.slice(0, 8)}</span>
                    )}
                  </td>
                  <td className="px-4 py-3">
                    <pre className="max-w-md overflow-x-auto rounded bg-zinc-50 px-2 py-1 text-[11px] text-zinc-600">
                      {JSON.stringify(r.details, null, 0)}
                    </pre>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}