<script lang="ts">
  import { error } from '@sveltejs/kit';
  import Table from '$lib/components/data-table/Table.svelte'
  import type { Column } from '$lib/components/data-table/types';
  import type { UserProfilePage } from "../+page";
  import { getUserFromLocalstorage as getUser } from '$lib/auth/session';

  export let data: UserProfilePage;
  const loggedInUser = getUser();
  if (loggedInUser === null) {
    throw error(401, 'You must be logged in to view this page.');
  }

  const columns: Column[] = [
      {
        field: 'id',
        heading: 'ID',
        type: 'number,'
      },
      {
        field: 'title',
        heading: 'Title',
        isLink: true,
        linkTarget: '/todos/%id%',
      },
      {
        field: 'done',
        heading: 'Done',
        type: 'boolean',
      },
      {
        field: 'created',
        heading: 'Created',
        type: 'date',
      },
      {
        field: 'updated',
        heading: 'Updated',
        type: 'date',
      },
      {
        field: 'finished',
        heading: 'Finished',
        type: 'date',
      },
  ];

  const table = {
    caption: loggedInUser.id === data.user.id ? 'My TODOs' : `${data.user.first_name} ${data.user.last_name}'s TODOs`,
    columns: loggedInUser.isAdmin ? columns : columns.slice(1, -1),
    getItemsEndpoint: data.endpointFactory.createReadTodosEndpoint(data.user.id),
    getItemCountEndpoint: data.endpointFactory.createReadTodoCountEndpoint(data.user.id),
    defaultSortField: 'updated',
    defaultSortOrder: 'desc',
  };
</script>

<Table {...table} />
