import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import type { components } from '../schema';
import { apiClient, useSelectedEnv } from './alertMeta';

export type AlertSilenceResponse = components['schemas']['AlertSilenceResponse'];
export type AlertSilenceRequest = components['schemas']['AlertSilenceRequest'];

// NOTE ON TYPES: the generated OpenAPI schema for env-scoped alert-silence
// endpoints emits `path?: never` plus a `query.env: Environment` parameter
// because the server resolves the env via the `@EnvPath` argument resolver,
// which the OpenAPI scanner does not recognise as a path variable. At runtime
// the URL template `{envSlug}` is substituted from `params.path.envSlug` by
// openapi-fetch regardless of what the TS types say; we therefore cast the
// call options to `any` on each call to bypass the generated type oddity.

/** List alert silences in the current env. */
export function useAlertSilences() {
  const env = useSelectedEnv();
  return useQuery({
    queryKey: ['alertSilences', env],
    enabled: !!env,
    queryFn: async () => {
      if (!env) throw new Error('no env');
      const { data, error } = await apiClient.GET(
        '/environments/{envSlug}/alerts/silences',
        {
          params: { path: { envSlug: env } },
        } as any,
      );
      if (error) throw error;
      return data as AlertSilenceResponse[];
    },
  });
}

/** Create a new alert silence in the current env. */
export function useCreateSilence() {
  const qc = useQueryClient();
  const env = useSelectedEnv();
  return useMutation({
    mutationFn: async (req: AlertSilenceRequest) => {
      if (!env) throw new Error('no env');
      const { data, error } = await apiClient.POST(
        '/environments/{envSlug}/alerts/silences',
        {
          params: { path: { envSlug: env } },
          body: req,
        } as any,
      );
      if (error) throw error;
      return data as AlertSilenceResponse;
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['alertSilences', env] });
    },
  });
}

/** Update an existing alert silence. */
export function useUpdateSilence(id: string) {
  const qc = useQueryClient();
  const env = useSelectedEnv();
  return useMutation({
    mutationFn: async (req: AlertSilenceRequest) => {
      if (!env) throw new Error('no env');
      const { data, error } = await apiClient.PUT(
        '/environments/{envSlug}/alerts/silences/{id}',
        {
          params: { path: { envSlug: env, id } },
          body: req,
        } as any,
      );
      if (error) throw error;
      return data as AlertSilenceResponse;
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['alertSilences', env] });
    },
  });
}

/** Delete an alert silence. */
export function useDeleteSilence() {
  const qc = useQueryClient();
  const env = useSelectedEnv();
  return useMutation({
    mutationFn: async (id: string) => {
      if (!env) throw new Error('no env');
      const { error } = await apiClient.DELETE(
        '/environments/{envSlug}/alerts/silences/{id}',
        {
          params: { path: { envSlug: env, id } },
        } as any,
      );
      if (error) throw error;
    },
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['alertSilences', env] });
    },
  });
}
