import { inject, Injectable } from '@angular/core';

import { Action, Selector, State, StateContext } from '@ngxs/store';
import { tap } from 'rxjs';

import { GetLanguageAction, SetDefaultLanguageAction } from '../action/language.action';
import { ILanguage } from '../interface/language.interface';
import { LanguageService } from '../services/language.service';

export class LanguageStateModel {
  language = {
    data: [] as ILanguage[],
    total: 0,
  };
  defaultLanguage: ILanguage | null;
}

@State<LanguageStateModel>({
  name: 'language',
  defaults: {
    language: {
      data: [],
      total: 0,
    },
    defaultLanguage: null,
  },
})
@Injectable()
export class LanguageState {
  private languageService = inject(LanguageService);

  @Selector()
  static language(state: LanguageStateModel) {
    return state.language;
  }

  @Selector()
  static defaultLanguage(state: LanguageStateModel) {
    return state.defaultLanguage;
  }

  @Action(GetLanguageAction)
  getLanguages(ctx: StateContext<LanguageStateModel>, action: GetLanguageAction) {
    return this.languageService.getLanguage(action.payload).pipe(
      tap({
        next: result => {
          ctx.patchState({
            language: {
              data: result.data,
              total: result?.total ? result?.total : result.data?.length,
            },
          });
        },
        error: err => {
          throw new Error(err?.error?.message);
        },
      }),
    );
  }

  @Action(SetDefaultLanguageAction)
  setDefaultLanguage(
    ctx: StateContext<LanguageStateModel>,
    { language }: SetDefaultLanguageAction,
  ) {
    ctx.patchState({
      defaultLanguage: language,
    });
  }
}
