import { type ColumnDef } from "@tanstack/react-table";
import { Badge } from "@/components/ui/badge";
import type { Audits } from "@/types/audit";

export const auditColumns: ColumnDef<Audits>[] = [
  {
    header: "Thời gian",
    accessorKey: "dateTime",
    cell: ({ getValue }) => {
      const v = getValue() as string;
      const d = v ? new Date(v) : null;
      return d ? (
        <div className="text-sm whitespace-nowrap">
          <div className="font-medium">{d.toLocaleDateString("vi-VN")}</div>
          <div className="text-muted-foreground text-xs">
            {d.toLocaleTimeString("vi-VN")}
          </div>
        </div>
      ) : (
        <span className="text-muted-foreground">—</span>
      );
    },
  },
  {
    header: "User",
    accessorKey: "username",
    cell: ({ getValue }) => (
      <span className="font-medium text-sm whitespace-nowrap">
        {getValue() as string}
      </span>
    ),
  },
  {
    header: "Loại",
    accessorKey: "apiCall",
    cell: ({ getValue }) => {
      const v = (getValue() as string) ?? "";
      if (!v) return <span className="text-muted-foreground">—</span>;
      return (
        <code className="text-xs bg-muted px-1.5 py-0.5 rounded whitespace-nowrap">
          {v}
        </code>
      );
    },
  },
  {
    header: "Hành động",
    accessorKey: "action",
    cell: ({ getValue }) => (
      <code className="text-xs bg-muted px-1.5 py-0.5 rounded whitespace-nowrap">
        {getValue() as string}
      </code>
    ),
  },
  {
    header: "URL",
    accessorKey: "url",
    cell: ({ getValue }) => (
      <code className="text-xs text-muted-foreground max-w-[180px] truncate block">
        {(getValue() as string) ?? "—"}
      </code>
    ),
  },
  {
    header: "Kết quả",
    accessorKey: "isSuccess",
    cell: ({ getValue }) => {
      const v = getValue();
      if (v == null) return <span className="text-muted-foreground">—</span>;
      return v ? (
        <Badge variant="outline" className="text-green-600 border-green-600 whitespace-nowrap">
          Thành công
        </Badge>
      ) : (
        <Badge variant="outline" className="text-red-600 border-red-600 whitespace-nowrap">
          Thất bại
        </Badge>
      );
    },
  },
  {
    header: "Nội dung request",
    accessorKey: "requestPayload",
    cell: ({ getValue }) => {
      const v = getValue() as string;
      if (!v) return <span className="text-muted-foreground">—</span>;
      let preview = v;
      try {
        preview = JSON.stringify(JSON.parse(v));
      } catch {}
      return (
        <span className="text-xs text-muted-foreground max-w-[200px] truncate block">
          {preview}
        </span>
      );
    },
  },
];