import {defineField, defineType} from "sanity";

const STATUS_OPTIONS = [
  {title: "En attente", value: "pending"},
  {title: "Publié", value: "approved"},
  {title: "Rejeté", value: "rejected"},
];

export const productReview = defineType({
  name: "productReview",
  title: "Avis produit",
  type: "document",
  fields: [
    defineField({
      name: "product",
      title: "Produit",
      type: "reference",
      to: [{type: "product"}],
      validation: (r) => r.required(),
    }),
    defineField({
      name: "rating",
      title: "Note",
      type: "number",
      options: {list: [1, 2, 3, 4, 5]},
      validation: (r) => r.required().min(1).max(5),
    }),
    defineField({name: "authorName", title: "Nom", type: "string", validation: (r) => r.required()}),
    defineField({name: "authorEmail", title: "Email (non affiché)", type: "string"}),
    defineField({name: "title", title: "Titre de l'avis", type: "string"}),
    defineField({name: "body", title: "Commentaire", type: "text", validation: (r) => r.required().max(2000)}),
    defineField({
      name: "status",
      title: "Statut",
      type: "string",
      options: {list: STATUS_OPTIONS},
      initialValue: "pending",
      validation: (r) => r.required(),
    }),
    defineField({name: "createdAt", title: "Date de soumission", type: "datetime", initialValue: () => new Date().toISOString()}),
  ],
  orderings: [
    {
      title: "Plus récent",
      name: "createdAtDesc",
      by: [{field: "createdAt", direction: "desc"}],
    },
  ],
  preview: {
    select: {
      title: "title",
      authorName: "authorName",
      rating: "rating",
      status: "status",
      productTitle: "product.title",
    },
    prepare: ({title, authorName, rating, status, productTitle}) => ({
      title: title || `${authorName} — ${"★".repeat(rating || 0)}`,
      subtitle: `${status} • ${productTitle || "Produit inconnu"}`,
    }),
  },
});
