import { AllocationStatus, UpdateAllocationSchema } from "@capakraken/shared";
import { z } from "zod";
import { PROJECT_BRIEF_SELECT, RESOURCE_BRIEF_SELECT, ROLE_BRIEF_SELECT } from "../db/selects.js";

export const DEMAND_INCLUDE = {
  project: { select: PROJECT_BRIEF_SELECT },
  roleEntity: { select: ROLE_BRIEF_SELECT },
  assignments: {
    include: {
      resource: { select: RESOURCE_BRIEF_SELECT },
      project: { select: PROJECT_BRIEF_SELECT },
      roleEntity: { select: ROLE_BRIEF_SELECT },
    },
  },
} as const;

export const ASSIGNMENT_INCLUDE = {
  resource: { select: RESOURCE_BRIEF_SELECT },
  project: { select: PROJECT_BRIEF_SELECT },
  roleEntity: { select: ROLE_BRIEF_SELECT },
  demandRequirement: {
    select: {
      id: true,
      projectId: true,
      startDate: true,
      endDate: true,
      hoursPerDay: true,
      percentage: true,
      role: true,
      roleId: true,
      headcount: true,
      status: true,
    },
  },
} as const;

export type AllocationListFilters = {
  projectId?: string | undefined;
  resourceId?: string | undefined;
  status?: AllocationStatus | undefined;
};

export type AllocationEntryUpdateInput = z.infer<typeof UpdateAllocationSchema>;

export type AssignmentResolutionInput = {
  assignmentId?: string | undefined;
  resourceId?: string | undefined;
  projectId?: string | undefined;
  startDate?: Date | undefined;
  endDate?: Date | undefined;
  selectionMode?: "WINDOW" | "EXACT_START" | undefined;
  excludeCancelled?: boolean | undefined;
};

export type CreateDemandDraftInput = {
  projectId: string;
  role?: string | undefined;
  roleId?: string | undefined;
  headcount?: number | undefined;
  hoursPerDay: number;
  startDate: Date;
  endDate: Date;
  budgetCents?: number | undefined;
  metadata?: Record<string, unknown> | undefined;
};

export function toIsoDate(value: Date) {
  return value.toISOString().slice(0, 10);
}

export function round1(value: number) {
  return Math.round(value * 10) / 10;
}

export function averagePerWorkingDay(totalHours: number, workingDays: number) {
  if (workingDays <= 0) {
    return 0;
  }
  return round1(totalHours / workingDays);
}
