import { ClubRequest } from '../models/index.js';

function completedRequestStateForTaskType(taskType) {
  switch (taskType) {
    case 'request_contact_reply':
      return { status: 'waiting', workflowStage: 'contact_replied' };
    case 'request_schedule_trial_training':
      return { status: 'in_progress', workflowStage: 'trial_training_scheduled' };
    case 'request_trial_training_follow_up':
      return { status: 'waiting', workflowStage: 'trial_training_feedback_recorded' };
    case 'request_membership_review':
      return { status: 'in_progress', workflowStage: 'membership_reviewed' };
    case 'membership_prepare_admission':
      return { status: 'in_progress', workflowStage: 'admission_prepared' };
    case 'membership_create_member_record':
      return { status: 'in_progress', workflowStage: 'member_record_created' };
    case 'membership_collect_sepa_mandate':
      return { status: 'in_progress', workflowStage: 'sepa_pending' };
    case 'membership_assign_fee':
      return { status: 'converted', workflowStage: 'onboarding_completed', closedAt: new Date() };
    case 'request_sponsoring_reply':
      return { status: 'waiting', workflowStage: 'sponsoring_contacted' };
    case 'sponsoring_prepare_offer':
      return { status: 'waiting', workflowStage: 'sponsoring_offer_prepared' };
    case 'sponsoring_follow_up':
      return { status: 'waiting', workflowStage: 'sponsoring_followed_up' };
    default:
      return null;
  }
}

class ClubWorkflowSourceService {
  async syncSourceStateForCompletedTask(task) {
    if (task.relatedEntityType !== 'club_request' || !task.relatedEntityId) {
      return null;
    }

    const requestState = completedRequestStateForTaskType(task.taskType);
    if (!requestState) {
      return null;
    }

    const request = await ClubRequest.findOne({
      where: {
        id: task.relatedEntityId,
        clubId: task.clubId,
      },
    });

    if (!request) {
      return null;
    }

    await request.update({
      status: requestState.status,
      workflowStage: requestState.workflowStage,
      closedAt: requestState.closedAt || null,
    });

    return {
      entityType: 'club_request',
      entityId: request.id,
      status: request.status,
      workflowStage: request.workflowStage,
    };
  }
}

export default new ClubWorkflowSourceService();
