import axiosServer from '../../../../src/axiosServer';
import NewPubPage from "../new";
const common = require('../../../../src/helpers/common');
export default NewPubPage;

import { Assignment, Shift, UserRole, AvailabilityType } from "prisma/prisma-client";
//import ProtectedRoute from '../../../../components/protectedRoute';

// import { monthNamesBG } from "~/src/helpers/const"
import { monthNamesBG } from "src/helpers/const";

function getShiftGroups(shifts: [Shift]) {

  const groupedShifts = shifts.reduce((groups, shift) => {
    // Extract the year and month from the shift date
    const yearMonth = shift.startTime.substring(0, 7)
    // Initialize the group for the year-month if it doesn't exist
    if (!groups[yearMonth]) {
      groups[yearMonth] = []
    }
    // Add the shift to the group
    groups[yearMonth].push(shift)
    // Return the updated groups object
    return groups
  }, {})

  // Sort the groups by year-month
  const sortedGroups = Object.keys(groupedShifts).sort((a, b) => {
    // Compare the year-month strings lexicographically
    if (a < b) return -1
    if (a > b) return 1
    return 0
  }).reduce((result, key) => {
    // Rebuild the object with the sorted keys
    result[key] = groupedShifts[key]
    return result
  }, {})
  return sortedGroups;
}

export const getServerSideProps = async (context) => {
  const axios = await axiosServer(context);

  const prisma = common.getPrismaClient();

  // const isAdmin = await ProtectedRoute.IsInRole(UserRole.ADMIN); does not work on server side
  context.res.setHeader("Cache-Control", "s-maxage=1, stale-while-revalidate");
  if (!context.query || !context.query.id) {
    return {
      props: {}
    };
  }
  const item = await prisma.publisher.findUnique({
    where: {
      id: context.query.id
    },
    include: {
      availabilities: true,
      assignments: {
        include: {
          shift: true
        }
      }
    }
  });
  if (!item) {
    const user = context.req.session?.user;
    if (!user) {
      return {
        // redirect to '/auth/signin'. assure it is not relative path
        redirect: {
          destination: process.env.NEXT_PUBLIC_PUBLIC_URL + "/auth/signin",
          permanent: false,
        }
      }
    }
    const message = encodeURIComponent(`Този имейл (${user?.email}) не е регистриран. Моля свържете се с администратора.`);
    return {
      redirect: {
        destination: `/message?message=${message}`,
        permanent: false,
      },
    };
  }
  // item.allShifts = item.assignments.map((a: Assignment[]) => a.shift);

  // ============================================================
  // don't show past availabilities (if user not admin) ToDo: add admin check
  // ============================================================
  item.availabilities = item.availabilities.filter((a) => new Date(a.startTime) >= new Date() || a.type == AvailabilityType.Weekly);
  item.assignments = item.assignments
    .sort((a, b) => b.startTime - a.startTime)
    .reduce((acc, assignment: Assignment) => {

      const date = new Date(assignment.shift.startTime);
      const year = date.getFullYear();
      const month = date.getMonth();
      const tabId = year + "-" + month;
      const tabName = monthNamesBG[month] + " " + year;
      const day = date.getDate();
      // console.log("shift: year: " + year + " month: " + month + " day: " + day);
      if (!acc.items[tabId]) {
        acc.items[tabId] = [];
      }
      if (!acc.items[tabId][day]) {
        acc.items[tabId][day] = [];
      }
      //remove duplicates
      if (acc.items[tabId][day].find(s => s.id == assignment.shift.id)) {
        return acc;
      }
      // acc.months = acc.months || [];
      if (!acc.months[tabId]) {
        acc.months[tabId] = [];
      }

      if (!acc.keys.includes(tabId)) {
        acc.months[tabId] = tabName;
        acc.keys.push(tabId);
      }

      acc.items[tabId][day].push({
        start: assignment.shift.startTime,
        end: assignment.shift.endTime,
        id: assignment.id,
        shiftId: assignment.shift.id,
        isConfirmed: assignment.isConfirmed ? true : false,
      });
      return acc;
    }, { items: {}, keys: [], months: {} });
  // console.log("server item:");
  // console.dir(item, { depth: null });
  return {
    props: {
      item: common.convertDatesToISOStrings(item),
    },
  };
};
