import Link from "next/link";
import { db } from "@/lib/db";
import { AdminOnlyGate } from "../AdminOnlyGate";

const ACTION_LABELS: Record<string, string> = {
  reject_label: "Rejected label",
  delete_label: "Deleted label",
  dismiss_flag: "Dismissed flag",
  ban_user: "Banned user",
  unban_user: "Unbanned user",
  set_user_role: "Changed user role",
  set_contributor_flag: "Changed contributor status",
  award_cellar_choice: "Awarded Cellar Choice",
  revoke_cellar_choice: "Revoked Cellar Choice",
  update_site_settings: "Updated site settings",
  create_api_key: "Created API key",
  revoke_api_key: "Revoked API key",
  apply_fix_suggestion: "Applied fix suggestion",
  reject_fix_suggestion: "Rejected fix suggestion",
};

export default async function AdminLogPage() {
  const entries = await db.moderationLog.findMany({
    orderBy: { createdAt: "desc" },
    take: 100,
    include: { actor: true },
  });

  return (
    <AdminOnlyGate>
    <div>
      <h1 className="font-heading text-3xl font-semibold text-terracotta">
        Moderation Log
      </h1>
      <p className="mt-2 text-charcoal/60">
        Audit trail of admin and moderator actions. Most recent 100 entries.
      </p>

      {entries.length === 0 ? (
        <p className="mt-8 text-charcoal/60">No actions logged yet.</p>
      ) : (
        <ul className="mt-8 flex flex-col gap-2">
          {entries.map((entry) => (
            <li
              key={entry.id}
              className="rounded-lg border border-charcoal/10 bg-warm-white p-3 text-sm"
            >
              <span className="text-charcoal/50">
                {entry.createdAt.toLocaleString()}
              </span>{" "}
              <strong className="text-charcoal">{entry.actor.username}</strong>{" "}
              <span className="text-charcoal">
                {ACTION_LABELS[entry.action] ?? entry.action}
              </span>{" "}
              {entry.targetType === "label" ? (
                <Link
                  href={`/labels/${entry.targetId}`}
                  className="text-terracotta hover:underline"
                >
                  ({entry.targetType})
                </Link>
              ) : (
                <span className="text-charcoal/60">
                  ({entry.targetType}: {entry.targetId})
                </span>
              )}
              {entry.detail && (
                <span className="text-charcoal/60"> &middot; {entry.detail}</span>
              )}
            </li>
          ))}
        </ul>
      )}
    </div>
    </AdminOnlyGate>
  );
}
