"use client";
import { movies } from "@/lib/db/schema";
import { createContext, FC, use, useState } from "react";

type Movie = typeof movies.$inferSelect;

type GlobalStore = {
  movies: Movie[];
  addMovie: (movie: Movie) => void;
  deleteMovie: (id: number) => void;
  updateMovie: (id: number, movie: Partial<Movie>) => void;
};

const globalStore = createContext<GlobalStore>({
  movies: [],
  addMovie: () => {},
  deleteMovie: () => {},
  updateMovie: () => {},
});

type Props = {
  children: React.ReactNode;
  initialMovies: GlobalStore["movies"];
};

export const GlobalStoreProvider: FC<Props> = ({ children, initialMovies }) => {
  const [movies, setMovies] = useState<GlobalStore["movies"]>(initialMovies);

  const addMovie = async (movie: Movie) => {
    if (movies.find((m) => m.id === movie.id)) return;

    setMovies((prev) => [...prev, movie]);
  };

  const deleteMovie = async (id: number) => {
    setMovies((prev) => prev.filter((m) => m.id !== id));
  };

  const updateMovie = async (id: number, movie: Partial<Movie>) => {
    setMovies((prev) =>
      prev.map((m) => (m.id === id ? { ...m, ...movie } : m))
    );
  };

  return (
    <globalStore.Provider
      value={{ movies, addMovie, deleteMovie, updateMovie }}
    >
      {children}
    </globalStore.Provider>
  );
};

export const useGlobalStore = () => {
  return use(globalStore);
};
