import { TaskService } from '../../../tasks/service';
import { ICONS } from '../../../utils/icons';
import { codeId, formatDDMM, italic } from '../../../utils/formatting';
import { resolveAndValidate, formatDue } from '../shared';

type Ctx = {
  sender: string;
  groupId: string;
  message: string;
};

type Msg = {
  recipient: string;
  message: string;
  mentions?: string[];
};

// ---------------------------------------------------------------------------
// Message builder
// ---------------------------------------------------------------------------

function unassignMessage(
  res: ReturnType<typeof TaskService.unassignTask>,
  resolvedId: number,
): string {
  const label = codeId(resolvedId, res.task?.display_code);
  const desc = res.task?.description || '(sin descripción)';
  const due = formatDue(res.task);

  switch (res.status) {
    case 'forbidden_personal':
      return '⚠️ No puedes soltar una tarea personal. Márcala como completada para eliminarla';

    case 'not_found':
      return `⚠️ Tarea ${codeId(resolvedId)} no encontrada.`;

    case 'completed':
      return `ℹ️ ${label} ya estaba completada — ${desc}${due}`;

    case 'not_assigned':
      return `ℹ️ ${label} no la tenías asignada — ${desc}${due}`;

    case 'unassigned': {
      if (res.now_unassigned) {
        return [
          `${ICONS.unassigned} ${label}`,
          desc,
          res.task?.due_date ? `${ICONS.date} ${formatDDMM(res.task!.due_date)}` : '',
          italic('queda sin responsable.'),
        ].filter(Boolean).join('\n');
      }
      return [
        `${ICONS.unassign} ${label}`,
        desc,
        res.task?.due_date ? `${ICONS.date} ${formatDDMM(res.task!.due_date)}` : '',
      ].filter(Boolean).join('\n');
    }

    default:
      return '⚠️ Estado inesperado al soltar la tarea.';
  }
}

// ---------------------------------------------------------------------------
// Handler
// ---------------------------------------------------------------------------

export async function handleSoltar(context: Ctx): Promise<Msg[]> {
  const tokens = (context.message || '').trim().split(/\s+/);
  const idInput = parseInt(tokens[2], 10);
  if (!idInput || Number.isNaN(idInput)) {
    return [{ recipient: context.sender, message: 'ℹ️ Uso: `t soltar 26`' }];
  }

  const rv = resolveAndValidate(idInput, context.sender);
  if ('error' in rv) {
    return [{ recipient: context.sender, message: rv.error }];
  }

  const res = TaskService.unassignTask(rv.resolvedId, context.sender);
  return [{ recipient: context.sender, message: unassignMessage(res, rv.resolvedId) }];
}
