import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { getDbWhatsAppPhoneNumbers, syncWhatsAppPhoneNumbers } from './service';
import type { WhatsAppPhoneNumber } from './interface';

// Query sent to GET /api/v1/whatsapp/phone-numbers (our whatsapp_phonenumbers table).
export interface PhoneNumbersQuery {
  page?: number;
  pageSize?: number;
  allocated?: string; // 'true' | 'false' | '' (all)
  status?: string;
  search?: string;
}

interface InitialState {
  phoneNumbers: WhatsAppPhoneNumber[];
  count: number;
  status: string;
  error: string;
  total: number; // total numbers matching the filters (page mode)
  statuses: string[]; // every status in the account, for the status filter
  lastQuery: PhoneNumbersQuery | null; // reused by refresh calls
}

const initialState: InitialState = {
  phoneNumbers: [],
  count: 0,
  status: 'loading',
  error: '',
  total: 0,
  statuses: [],
  lastQuery: null,
};

// dispatch(fetch(query)) loads that page; dispatch(fetch({ refresh: true })) reloads the last query.
export const fetchWhatsAppPhoneNumbers = createAsyncThunk<
  { response: any; query: PhoneNumbersQuery | null },
  (PhoneNumbersQuery & { refresh?: boolean }) | void
>('phoneNumbers/fetchWhatsAppPhoneNumbers', async (arg, { getState }) => {
  let query: PhoneNumbersQuery | null = null;
  if (arg && (arg as any).refresh) {
    query = (getState() as any).phoneNumbers?.lastQuery ?? null;
  } else if (arg) {
    query = arg as PhoneNumbersQuery;
  }
  const response = await getDbWhatsAppPhoneNumbers(query || undefined);
  return { response, query };
});

// Sync with the WhatsApp Cloud API, then show the refreshed DB list returned by the sync call.
// Pass a query to choose what that list shows (the page passes the unfiltered first page); without one it
// keeps the current filters/page.
export const syncWhatsAppPhoneNumbersThunk = createAsyncThunk<
  { response: any; query: PhoneNumbersQuery | null },
  PhoneNumbersQuery | void
>('phoneNumbers/syncWhatsAppPhoneNumbers', async (arg, { getState }) => {
  const query: PhoneNumbersQuery | null =
    (arg as PhoneNumbersQuery | undefined) ?? (getState() as any).phoneNumbers?.lastQuery ?? null;
  const response = await syncWhatsAppPhoneNumbers(query || undefined);
  return { response, query };
});

const applyList = (
  state: InitialState,
  action: { payload: { response: any; query: PhoneNumbersQuery | null } }
) => {
  const body = action.payload?.response?.data;
  state.status = 'succeeded';
  state.phoneNumbers = body?.data || [];
  state.count = body?.count || (body?.data?.length ?? 0);
  state.total = body?.meta?.total ?? state.count;
  if (Array.isArray(body?.statuses)) state.statuses = body.statuses;
  state.lastQuery = action.payload?.query ?? null;
};

const phoneNumbersSlice = createSlice({
  name: 'phoneNumbers',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchWhatsAppPhoneNumbers.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(fetchWhatsAppPhoneNumbers.fulfilled, applyList)
      .addCase(fetchWhatsAppPhoneNumbers.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message ?? 'An error occurred';
      })
      // the sync response carries the refreshed DB list, so it is applied exactly like a normal fetch
      .addCase(syncWhatsAppPhoneNumbersThunk.fulfilled, applyList);
  },
});

export default phoneNumbersSlice.reducer;
