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

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

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

export async function handleSoltar(context: Ctx): Promise<Msg[]> {
  const tokens = (context.message || '').trim().split(/\s+/);

  const idToken = tokens[2];
  const idInput = idToken ? parseInt(idToken, 10) : NaN;
  if (!idInput || Number.isNaN(idInput)) {
    return [{
      recipient: context.sender,
      message: 'ℹ️ Uso: `/t soltar 26`'
    }];
  }

  const resolvedId = resolveTaskIdFromInput(idInput);
  if (!resolvedId) {
    return [{
      recipient: context.sender,
      message: `⚠️ Tarea ${codeId(idInput)} no encontrada.`
    }];
  }

  const task = TaskService.getTaskById(resolvedId);
  if (!task) {
    return [{
      recipient: context.sender,
      message: `⚠️ Tarea ${codeId(resolvedId)} no encontrada.`
    }];
  }

  if (!enforceMembership(context.sender, task)) {
    return [{
      recipient: context.sender,
      message: '⚠️ No puedes soltar esta tarea porque no eres de este grupo.'
    }];
  }

  const res = TaskService.unassignTask(resolvedId, context.sender);
  const due = res.task?.due_date ? ` — ${ICONS.date} ${formatDDMM(res.task?.due_date)}` : '';

  if (res.status === 'forbidden_personal') {
    return [{
      recipient: context.sender,
      message: '⚠️ No puedes soltar una tarea personal. Márcala como completada para eliminarla'
    }];
  }

  if (res.status === 'not_found') {
    return [{
      recipient: context.sender,
      message: `⚠️ Tarea ${codeId(resolvedId)} no encontrada.`
    }];
  }
  if (res.status === 'completed') {
    return [{
      recipient: context.sender,
      message: `ℹ️ ${codeId(resolvedId, res.task?.display_code)} ya estaba completada — ${res.task?.description || '(sin descripción)'}${due}`
    }];
  }
  if (res.status === 'not_assigned') {
    return [{
      recipient: context.sender,
      message: `ℹ️ ${codeId(resolvedId, res.task?.display_code)} no la tenías asignada — ${res.task?.description || '(sin descripción)'}${due}`
    }];
  }

  if (res.now_unassigned) {
    const lines = [
      `${ICONS.unassigned} ${codeId(resolvedId, res.task?.display_code)}`,
      `${res.task?.description || '(sin descripción)'}`,
      res.task?.due_date ? `${ICONS.date} ${formatDDMM(res.task?.due_date)}` : '',
      italic('queda sin responsable.')
    ].filter(Boolean);
    return [{
      recipient: context.sender,
      message: lines.join('\n')
    }];
  }

  const lines = [
    `${ICONS.unassign} ${codeId(resolvedId, res.task?.display_code)}`,
    `${res.task?.description || '(sin descripción)'}`,
    res.task?.due_date ? `${ICONS.date} ${formatDDMM(res.task?.due_date)}` : ''
  ].filter(Boolean);
  return [{
    recipient: context.sender,
    message: lines.join('\n')
  }];
}
