// reducers/failedJobsReducer.ts
import { REHYDRATE } from 'redux-persist';
import {
    REMOVE_ALL_FAILED_JOB,
    REMOVE_FAILED_JOB,
    SUBMIT_AUDIT_FAILED,
    SUBMIT_CHECKLIST_FAILED,
    SUBMIT_INCIDENT_FAILED,
    SUBMIT_INCIDENT_SUCCESS,
    SUBMIT_INSPECTION_FAILED,
    SUBMIT_PERMIT_FAILED,
} from '../actions/types';

// =======================
// Types
// =======================
export interface FailedJob {
  id: number;
  title: string;
  data: Record<string, any>;
  url: string;
}

export interface FailedJobsState {
  jobs: FailedJob[];
}

// =======================
// Meta for failed actions
// =======================
interface FailedJobMeta {
  title: string;
  data: Record<string, any>;
  url: string;
}

// =======================
// Action types
// =======================
type FailedJobsAction =
  | { type: typeof REHYDRATE; payload?: { failedJobsData?: FailedJobsState } }
  | { type: typeof SUBMIT_INCIDENT_FAILED | typeof SUBMIT_AUDIT_FAILED | typeof SUBMIT_INSPECTION_FAILED | typeof SUBMIT_CHECKLIST_FAILED | typeof SUBMIT_PERMIT_FAILED; meta: FailedJobMeta }
  | { type: typeof SUBMIT_INCIDENT_SUCCESS; payload: { data?: { status?: string; msg?: string } }; meta: FailedJobMeta }
  | { type: typeof REMOVE_FAILED_JOB; payload: { id: number } }
  | { type: typeof REMOVE_ALL_FAILED_JOB };

// =======================
// Initial State
// =======================
const initialState: FailedJobsState = {
  jobs: [],
};

// =======================
// Reducer
// =======================
export const failedJobsData = (
  state: FailedJobsState = initialState,
  action: FailedJobsAction
): FailedJobsState => {
  switch (action.type) {
    case REHYDRATE:
      return action.payload?.failedJobsData ?? state;

    // Failed jobs
    case SUBMIT_INCIDENT_FAILED:
    case SUBMIT_AUDIT_FAILED:
    case SUBMIT_INSPECTION_FAILED:
    case SUBMIT_CHECKLIST_FAILED:
    case SUBMIT_PERMIT_FAILED: {
      try {
        const newJob: FailedJob = {
          id: Date.now(),
          title: action.meta.title,
          data: { ...action.meta.data },
          url: action.meta.url,
        };
        return { jobs: [...state.jobs, newJob] };
      } catch {
        return state;
      }
    }

    // Incident success but error status
    case SUBMIT_INCIDENT_SUCCESS: {
      try {
        if (action.payload?.data?.status === 'error') {
          const msg = action.payload.data.msg ?? '';
          const newJob: FailedJob = {
            id: Date.now(),
            title: `${action.meta.title} ${msg}`,
            data: { ...action.meta.data },
            url: action.meta.url,
          };
          return { jobs: [...state.jobs, newJob] };
        }
        return state;
      } catch {
        return state;
      }
    }

    // Remove jobs
    case REMOVE_FAILED_JOB:
      return { jobs: state.jobs.filter(job => job.id !== action.payload.id) };

    case REMOVE_ALL_FAILED_JOB:
      return { jobs: [] };

    default:
      return state;
  }
};
