'use client';

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import type {
  CreateStoreSitePagePayload,
  StoreSite,
  StoreSitePage,
  UpdateStoreSitePagePayload,
  UpdateStoreSitePayload,
} from '@alqove/api-client';
import { api } from '@/lib/api';
import { useSelectedStoreId } from '@/lib/stores/store-context';

export function useStoreId(): string | null {
  return useSelectedStoreId();
}

export function siteQueryKey(storeId: string | null) {
  return ['seller-store-site', storeId] as const;
}

/**
 * The site endpoint provisions on first call, so this doubles as "create my
 * website if I don't have one yet" — the editor never opens on an empty state.
 */
export function useStoreSite(storeId: string | null) {
  return useQuery({
    queryKey: siteQueryKey(storeId),
    enabled: !!storeId,
    queryFn: () => api.storefront.getSite(storeId!),
  });
}

export function useSiteMutations(storeId: string | null) {
  const qc = useQueryClient();
  const invalidate = () => qc.invalidateQueries({ queryKey: siteQueryKey(storeId) });

  const updateSite = useMutation({
    mutationFn: (payload: UpdateStoreSitePayload) => api.storefront.updateSite(storeId!, payload),
    onSuccess: invalidate,
  });

  const updateSlug = useMutation({
    mutationFn: (slug: string) => api.storefront.updateSlug(storeId!, slug),
    onSuccess: invalidate,
  });

  const createPage = useMutation({
    mutationFn: (payload: CreateStoreSitePagePayload) =>
      api.storefront.pages.create(storeId!, payload),
    onSuccess: invalidate,
  });

  const updatePage = useMutation({
    mutationFn: ({ pageId, payload }: { pageId: string; payload: UpdateStoreSitePagePayload }) =>
      api.storefront.pages.update(storeId!, pageId, payload),
    onSuccess: invalidate,
  });

  const deletePage = useMutation({
    mutationFn: (pageId: string) => api.storefront.pages.remove(storeId!, pageId),
    onSuccess: invalidate,
  });

  const reorderPages = useMutation({
    mutationFn: (pageIds: string[]) => api.storefront.pages.reorder(storeId!, pageIds),
    onSuccess: invalidate,
  });

  return { updateSite, updateSlug, createPage, updatePage, deletePage, reorderPages };
}

export function useDomainMutations(storeId: string | null) {
  const qc = useQueryClient();
  const invalidate = () => qc.invalidateQueries({ queryKey: siteQueryKey(storeId) });

  const addDomain = useMutation({
    mutationFn: (hostname: string) => api.storefront.domains.create(storeId!, hostname),
    onSuccess: invalidate,
  });

  const verifyDomain = useMutation({
    mutationFn: (domainId: string) => api.storefront.domains.verify(storeId!, domainId),
    // The API answers 422 while DNS hasn't propagated, which lands here; the
    // domain row still needs refreshing so `last_check_error` updates.
    onSettled: invalidate,
  });

  const makePrimary = useMutation({
    mutationFn: (domainId: string) => api.storefront.domains.makePrimary(storeId!, domainId),
    onSuccess: invalidate,
  });

  const removeDomain = useMutation({
    mutationFn: (domainId: string) => api.storefront.domains.remove(storeId!, domainId),
    onSuccess: invalidate,
  });

  return { addDomain, verifyDomain, makePrimary, removeDomain };
}

export function sitePages(site: StoreSite | undefined): StoreSitePage[] {
  return site?.pages ?? [];
}

/** First validation message from an API error, if any. */
export function firstError(error: unknown): string | null {
  if (!error || typeof error !== 'object') return null;
  const err = error as { message?: string; errors?: Record<string, string[]> };
  const fieldError = Object.values(err.errors ?? {})[0]?.[0];
  return fieldError ?? err.message ?? null;
}
