// src/client/entities/employee/model/useEmployeeStatus.ts
// Composable for computing employee account status and scheduled actions

import { computed, type ComputedRef } from 'vue';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc.js';
import timezone from 'dayjs/plugin/timezone.js';
import type { Employee } from '@shared/contracts/personnel';

dayjs.extend(utc);
dayjs.extend(timezone);

export interface AccountStatus {
  text: string;
  color: 'green' | 'red' | 'orange';
}

export interface ScheduledAction {
  text: string;
  date: string;
  hasAction: boolean;
}

export function useEmployeeStatus(employee: () => Employee | undefined) {

  // Computed property for account status (dynamic status text and color)
  const accountStatus: ComputedRef<AccountStatus> = computed(() => {
    const emp = employee();
    if (!emp) {
      return { text: 'Учетная запись активна', color: 'green' };
    }

    const today = dayjs().tz('Europe/Moscow').startOf('day').toDate();

    // Check for scheduled termination (archivedAt in future) - takes precedence
    if (emp.archivedAt) {
      const archivedDate = dayjs(emp.archivedAt).tz('Europe/Moscow').startOf('day').toDate();
      if (archivedDate > today) {
        return {
          text: `Сотрудник будет уволен с ${formatDate(emp.archivedAt)}`,
          color: 'orange'
        };
      }
    }

    // If employee is fired (and archivedAt is today or in the past)
    if (emp.isFired === true) {
      return { text: 'Учетная запись отключена', color: 'red' };
    }

    // Default: active account
    return { text: 'Учетная запись активна', color: 'green' };
  });

  // Computed property for scheduled action
  const scheduledAction: ComputedRef<ScheduledAction> = computed(() => {
    const emp = employee();
    if (!emp) {
      return { text: '', date: '', hasAction: false };
    }

    const today = dayjs().tz('Europe/Moscow').startOf('day').toDate();

    // Check for future fire date (archivedAt in future) - regardless of isFired status
    if (emp.archivedAt) {
      const archivedDate = dayjs(emp.archivedAt).tz('Europe/Moscow').startOf('day').toDate();
      if (archivedDate > today) {
        return {
          text: 'Будет уволен с',
          date: formatDate(emp.archivedAt),
          hasAction: true
        };
      }
    }

    // Check for future rehire date
    // Note: Never show "Будет восстановлен с" for fired employees (even if createdAt is in future)
    // This prevents displaying incorrect information when employee is fired
    // No action needed here - return empty

    return { text: '', date: '', hasAction: false };
  });

  // Format date to Russian locale
  const formatDate = (dateString: string) => {
    return dayjs(dateString).tz('Europe/Moscow').format('DD.MM.YYYY');
  };

  return {
    accountStatus,
    scheduledAction,
  };
}
