import { writable } from 'svelte/store';

export type MockPageStoreValue = {
  url: URL;
  params: Record<string, string>;
  route: {
    id: string | null;
  };
  status: number;
  error: App.Error | null;
  data: Record<string, unknown>;
  form: Record<string, unknown> | null;
  state: Record<string, unknown>;
};

export function createMockPage(
  url = 'https://www.goodwalk.co.nz/',
  overrides: Partial<MockPageStoreValue> = {}
): MockPageStoreValue {
  return {
    url: new URL(url),
    params: {},
    route: { id: null },
    status: 200,
    error: null,
    data: {},
    form: null,
    state: {},
    ...overrides
  };
}

export const pageStore = writable<MockPageStoreValue>(createMockPage());
export type MockNavigatingStoreValue = {
  from: { url: URL } | null;
  to: { url: URL } | null;
} | null;

export const navigatingStore = writable<MockNavigatingStoreValue>(null);
const updatedWritable = writable(false);

export const updatedStore = {
  subscribe: updatedWritable.subscribe,
  check: async () => false
};

export function setMockPage(url: string, overrides: Partial<MockPageStoreValue> = {}) {
  pageStore.set(createMockPage(url, overrides));
}

export function resetMockPage() {
  pageStore.set(createMockPage());
}

export function setMockNavigating(
  to: string,
  from = 'https://www.goodwalk.co.nz/'
) {
  navigatingStore.set({
    from: { url: new URL(from) },
    to: { url: new URL(to) }
  });
}

export function resetMockNavigating() {
  navigatingStore.set(null);
}
