/**
 * React hooks for {{ model_name }} using REST API.
 *
 * ⚠️ AUTO-GENERATED BY PRISM - DO NOT EDIT
 */

import { useState, useEffect, useCallback } from 'react';
import type { {{ model_name }}, {{ model_name }}Create, {{ model_name }}Update, PaginationParams, PaginatedResponse } from '../types/generated';

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8000';

/**
 * Hook for fetching a single {{ model_name }} by ID.
 */
export function use{{ model_name }}(id: number | null) {
  const [data, setData] = useState<{{ model_name }} | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

  const fetch{{ model_name }} = useCallback(async () => {
    if (id === null) return;
    setLoading(true);
    try {
      const response = await fetch(`${API_URL}/{{ kebab_name }}/${id}`);
      if (!response.ok) throw new Error('Failed to fetch');
      const result = await response.json();
      setData(result);
      setError(null);
    } catch (e) {
      setError(e as Error);
    } finally {
      setLoading(false);
    }
  }, [id]);

  useEffect(() => {
    fetch{{ model_name }}();
  }, [fetch{{ model_name }}]);

  return { data, loading, error, refetch: fetch{{ model_name }} };
}

/**
 * Hook for fetching a list of {{ plural_name }}.
 */
export function use{{ model_name }}List(pagination?: PaginationParams) {
  const [data, setData] = useState<{{ model_name }}[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);
  const [totalCount, setTotalCount] = useState(0);
  const [pages, setPages] = useState(0);

  const page = pagination?.page ?? 1;
  const pageSize = pagination?.pageSize ?? 20;

  const fetchList = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: String(page),
        page_size: String(pageSize),
      });
      const response = await fetch(`${API_URL}/{{ kebab_name }}?${params}`);
      if (!response.ok) throw new Error('Failed to fetch');
      const result: PaginatedResponse<{{ model_name }}> = await response.json();
      setData(result.items);
      setTotalCount(result.total);
      setPages(result.pages);
      setError(null);
    } catch (e) {
      setError(e as Error);
    } finally {
      setLoading(false);
    }
  }, [page, pageSize]);

  useEffect(() => {
    fetchList();
  }, [fetchList]);

  return {
    data,
    loading,
    error,
    totalCount,
    hasNextPage: page < pages,
    hasPreviousPage: page > 1,
    refetch: fetchList,
  };
}

/**
 * Hook for {{ model_name }} mutations.
 */
export function use{{ model_name }}Mutations() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);

{%- if ops_create %}

  const create = async (data: {{ model_name }}Create): Promise<{{ model_name }} | null> => {
    setLoading(true);
    try {
      const response = await fetch(`${API_URL}/{{ kebab_name }}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      });
      if (!response.ok) throw new Error('Failed to create');
      const result = await response.json();
      setError(null);
      return result;
    } catch (e) {
      setError(e as Error);
      return null;
    } finally {
      setLoading(false);
    }
  };
{%- endif %}
{%- if ops_update %}

  const update = async (id: number, data: {{ model_name }}Update): Promise<{{ model_name }} | null> => {
    setLoading(true);
    try {
      const response = await fetch(`${API_URL}/{{ kebab_name }}/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      });
      if (!response.ok) throw new Error('Failed to update');
      const result = await response.json();
      setError(null);
      return result;
    } catch (e) {
      setError(e as Error);
      return null;
    } finally {
      setLoading(false);
    }
  };
{%- endif %}
{%- if ops_delete %}

  const remove = async (id: number): Promise<boolean> => {
    setLoading(true);
    try {
      const response = await fetch(`${API_URL}/{{ kebab_name }}/${id}`, {
        method: 'DELETE',
      });
      if (!response.ok) throw new Error('Failed to delete');
      setError(null);
      return true;
    } catch (e) {
      setError(e as Error);
      return false;
    } finally {
      setLoading(false);
    }
  };
{%- endif %}

  return {
{%- if ops_create %}
    create,
{%- endif %}
{%- if ops_update %}
    update,
{%- endif %}
{%- if ops_delete %}
    remove,
{%- endif %}
    loading,
    error,
  };
}

/**
 * Combined hook for all {{ model_name }} operations.
 */
export function use{{ model_name }}s(pagination?: PaginationParams) {
  const list = use{{ model_name }}List(pagination);
  const mutations = use{{ model_name }}Mutations();

  return {
    ...list,
    ...mutations,
  };
}
