<script lang="ts">
  import { uuid } from '$lib/stores/uuid';
  import { getApiUrl } from '$lib/scripts/upstream';
  import type { ApiResponse, StaffLdb } from '@owlboard/ts-types';

  export let station: string;
  export let title: string | undefined = 'Loading...';
  export let error = {
    state: false,
    name: 'none',
  }

  async function fetchStaffLdb(station: string) {
    const url = `${getApiUrl()}/api/v2/live/station/${station}/staff`;
    const options = {
      method: 'GET',
      headers: {
        uuid: $uuid
      }
    };
    const res = await fetch(url, options);
    let jsonData: ApiResponse<StaffLdb>;
    if (res.status === 200) {
      jsonData = await res.json();
      title = jsonData.data?.locationName;
      error.state = false;
    } else if (res.status === 401) {
      console.log(`Request Status: ${res.status}`);
      title = 'Unauthorised';
      error = {
        state: true,
        name: 'unauthorized',
      }
    }
  }
</script>

{#await fetchStaffLdb(station)}
  Loading
{:then data}
  Loaded {JSON.stringify(data)}
{:catch}
  Error Loading
{/await}

{#if error.state}
{#if error.name === 'unauthorized'}
<p>Error: {error.name.toLocaleUpperCase()}</p>
{/if}
{/if}
