import { prisma } from './prisma';

export const teamMemberSelect = {
  id: true,
  name: true,
  rank: true,
  role: true,
  cell: true,
  contact: true,
  photoUrl: true,
  sortOrder: true,
} as const;

export const milestoneInclude = {
  pmMember: { select: teamMemberSelect },
  milestoneAssignees: {
    include: { member: { select: teamMemberSelect } },
  },
} as const;

export const taskInclude = {
  assignee: { select: { id: true, name: true, department: true } },
  creator: { select: { id: true, name: true } },
  pmMember: { select: teamMemberSelect },
  taskAssignees: {
    include: { member: { select: teamMemberSelect } },
  },
  milestones: {
    orderBy: { order: 'asc' as const },
    select: {
      id: true,
      title: true,
      progress: true,
      startDate: true,
      dueDate: true,
      periodEntries: true,
      order: true,
    },
  },
  _count: { select: { files: true, details: true } },
} as const;

export const taskDetailInclude = {
  assignee: { select: { id: true, name: true, department: true } },
  creator: { select: { id: true, name: true } },
  pmMember: { select: teamMemberSelect },
  taskAssignees: {
    include: { member: { select: teamMemberSelect } },
  },
  details: {
    orderBy: { createdAt: 'desc' as const },
    include: { author: { select: { id: true, name: true } } },
  },
  kpiMetrics: true,
  files: true,
  milestones: {
    orderBy: { order: 'asc' as const },
    include: milestoneInclude,
  },
};

export function formatMilestone<T extends Record<string, unknown>>(milestone: T) {
  const { milestoneAssignees, ...rest } = milestone as T & {
    milestoneAssignees?: Array<{ member: unknown }>;
  };
  const assigneeMembers = (milestoneAssignees ?? []).map((ma) => ma.member);
  return { ...rest, assigneeMembers };
}

export function formatTask<T extends Record<string, unknown>>(task: T) {
  const { taskAssignees, milestones, ...rest } = task as T & {
    taskAssignees?: Array<{ member: unknown }>;
    milestones?: Array<Record<string, unknown>>;
  };
  const assigneeMembers = (taskAssignees ?? []).map((ta) => ta.member);
  const formattedMilestones = milestones?.map((m) => formatMilestone(m));
  return {
    ...rest,
    assigneeMembers,
    ...(formattedMilestones !== undefined ? { milestones: formattedMilestones } : {}),
  };
}

export async function syncTaskMembers(
  taskId: string,
  pmMemberId: string | null | undefined,
  assigneeMemberIds: string[] | undefined,
) {
  if (pmMemberId !== undefined) {
    await prisma.task.update({
      where: { id: taskId },
      data: { pmMemberId: pmMemberId || null },
    });
  }

  if (assigneeMemberIds !== undefined) {
    await prisma.taskAssignee.deleteMany({ where: { taskId } });
    const ids = [...new Set(assigneeMemberIds.filter(Boolean))];
    if (ids.length > 0) {
      await prisma.taskAssignee.createMany({
        data: ids.map((memberId) => ({ taskId, memberId })),
      });
    }
  }
}

export function parseMemberIds(body: Record<string, unknown>): string[] | undefined {
  if (body.assigneeMemberIds === undefined) return undefined;
  const raw = body.assigneeMemberIds;
  if (!Array.isArray(raw)) return [];
  return raw.map(String).filter(Boolean);
}
