/**
 * Reusable mutation hooks for poo and location CRUD (M2-T10, reused by T09).
 *
 * Contract (orchestrator-decisions.md §13):
 * - useUpdatePoo / useDeletePoo   — PK = timestamp, path /api/poo/{timestamp}
 * - useUpdateLocation / useDeleteLocation — PK = person+datetime, path /api/locations/{person}/{datetime}
 * - Path params are passed as raw strings; openapi-fetch's defaultPathSerializer
 *   already calls encodeURIComponent once per simple {param} segment.
 *   Do NOT call encodeURIComponent here — that would produce double-encoding.
 * - On success each hook invalidates the shared query-key prefix ('poo' or 'locations')
 *   so both list and map views refresh automatically.
 */

import { useMutation, useQueryClient } from '@tanstack/react-query'
import apiClient from '../api/client'
import type { components } from '../api/schema.d.ts'

// Re-export record types so T09 can import them from one place.
export type PooRecord = components['schemas']['PooRecord']
export type LocationRecord = components['schemas']['LocationRecord']
export type PooUpdateBody = components['schemas']['PooUpdateRequest']
export type LocationUpdateBody = components['schemas']['LocationUpdateRequest']

// ---------------------------------------------------------------------------
// Poo hooks
// ---------------------------------------------------------------------------

/** Update non-PK fields of a single poo record. */
export function useUpdatePoo() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: ({ timestamp, body }: { timestamp: string; body: PooUpdateBody }) =>
      apiClient.PATCH('/api/poo/{timestamp}', {
        params: { path: { timestamp } },
        body,
      }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['poo'] }),
  })
}

/** Delete a single poo record by its PK (timestamp). */
export function useDeletePoo() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (timestamp: string) =>
      apiClient.DELETE('/api/poo/{timestamp}', {
        params: { path: { timestamp } },
      }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['poo'] }),
  })
}

// ---------------------------------------------------------------------------
// Location hooks
// ---------------------------------------------------------------------------

/** Update non-PK fields of a single location record. */
export function useUpdateLocation() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: ({
      person,
      datetime,
      body,
    }: {
      person: string
      datetime: string
      body: LocationUpdateBody
    }) =>
      apiClient.PATCH('/api/locations/{person}/{datetime}', {
        params: {
          path: {
            person,
            datetime,
          },
        },
        body,
      }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['locations'] }),
  })
}

/** Delete a single location record by its composite PK (person + datetime). */
export function useDeleteLocation() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: ({ person, datetime }: { person: string; datetime: string }) =>
      apiClient.DELETE('/api/locations/{person}/{datetime}', {
        params: {
          path: {
            person,
            datetime,
          },
        },
      }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['locations'] }),
  })
}
