import { NativeBridgeService } from '@/core/services';
import { defaultBaseStateData, EntityState, EntityStore } from '@/core/state';
import { HttpErrorResponse } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { IDeviceProfileResponse } from '../models';

interface DeviceInfoState extends EntityState<IDeviceProfileResponse> {}

@Injectable({
  providedIn: 'root',
})
export class DeviceInfoStore extends EntityStore<IDeviceProfileResponse, DeviceInfoState> {
  private readonly nativeBridgeService = inject(NativeBridgeService);

  constructor() {
    super({
      ...defaultBaseStateData,
    });
  }

  async getData() {
    this.patchState({ loading: true });
    if (this.nativeBridgeService.isEnabled()) {
      const deviceInfoRes = await this.nativeBridgeService.getDeviceInfo();
      if (deviceInfoRes.success && deviceInfoRes.data) {
        const deviceInfo = deviceInfoRes.data;
        this.setEntity({
          deviceName: deviceInfo.deviceName,
          deviceId: deviceInfo.androidId,
        });
      } else {
        this.setError(
          new HttpErrorResponse({ error: deviceInfoRes.error || 'Failed to get device info' }),
        );
      }
    }
    this.patchState({ loading: true });
  }

  override reset(): void {
    this.setState({
      ...defaultBaseStateData,
    });
  }
}
