"use client";
import { create } from "zustand";
import { persist } from "zustand/middleware";
import type { Car } from "@/lib/types";
import { getCarHeroImage } from "@/lib/carImage";

export interface OwnedCarEntry extends Pick<
  Car,
  "id" | "name" | "brand" | "model" | "priceMin" | "priceMax" |
  "fuelType" | "bodyType" | "transmission" | "rating" | "year" | "slug"
> {
  imageUrl?:      string | null;
  primaryImage?:  string | null;
  imageGallery?:  Car["imageGallery"];
  images?:        Car["images"];
  addedAt:        string;          // ISO timestamp
  purchaseYear?: number;       // year the user bought it
  notes?:     string;          // optional personal note
}

interface OwnedCarsStore {
  items:       OwnedCarEntry[];
  add:         (car: Car) => void;
  remove:      (id: string) => void;
  has:         (id: string) => boolean;
  setPurchaseYear: (id: string, year: number) => void;
  setNotes:    (id: string, notes: string) => void;
  clear:       () => void;
}

export const useOwnedCarsStore = create<OwnedCarsStore>()(
  persist(
    (set, get) => ({
      items: [],

      add: (car) =>
        set((s) => {
          if (s.items.find((c) => c.id === car.id)) return s;
          const entry: OwnedCarEntry = {
            id:           car.id,
            name:         car.name,
            brand:        car.brand,
            model:        car.model,
            priceMin:     car.priceMin,
            priceMax:     car.priceMax,
            fuelType:     car.fuelType,
            bodyType:     car.bodyType,
            transmission: car.transmission,
            rating:       car.rating,
            year:         car.year,
            slug:         car.slug,
            primaryImage: car.primaryImage ?? null,
            imageGallery: car.imageGallery,
            images:       car.images,
            imageUrl:     getCarHeroImage(car),
            addedAt:      new Date().toISOString(),
          };
          return { items: [...s.items, entry] };
        }),

      remove: (id) => set((s) => ({ items: s.items.filter((c) => c.id !== id) })),

      has: (id) => get().items.some((c) => c.id === id),

      setPurchaseYear: (id, year) =>
        set((s) => ({
          items: s.items.map((c) => c.id === id ? { ...c, purchaseYear: year } : c),
        })),

      setNotes: (id, notes) =>
        set((s) => ({
          items: s.items.map((c) => c.id === id ? { ...c, notes } : c),
        })),

      clear: () => set({ items: [] }),
    }),
    { name: "drivehub-owned-cars" }
  )
);
