import { Injectable } from '@nestjs/common';
import { AccountProfileService } from '../auth/account_profile.service';
import { EconomyService } from './economy.service';
import { InventoryService } from './inventory.service';
import { PlayerSnapshotPayload } from './player.types';
import { UpdatePlayerProfileAssetsDto } from './dto/update_player_profile_assets.dto';

@Injectable()
export class PlayerStateService {
  constructor(
    private readonly accountProfileService: AccountProfileService,
    private readonly economyService: EconomyService,
    private readonly inventoryService: InventoryService,
  ) {}

  async getSnapshot(userId: bigint): Promise<PlayerSnapshotPayload> {
    const [accountProfile, wallet, inventory] = await Promise.all([
      this.accountProfileService.getAccountProfile(userId),
      this.economyService.getWallet(userId),
      this.inventoryService.listInventory(userId),
    ]);
    const selectedSkinId = accountProfile.profile.skin_id || '';

    return {
      user: accountProfile.user,
      profile: {
        user_id: accountProfile.profile.user_id,
        selected_skin_id: selectedSkinId,
        avatar_id: accountProfile.profile.avatar_id,
        avatar_url: accountProfile.profile.avatar_url,
        avatar_base64: accountProfile.profile.avatar_base64,
        current_map: accountProfile.profile.current_map,
        pos_x: accountProfile.profile.pos_x,
        pos_y: accountProfile.profile.pos_y,
        status: accountProfile.profile.status,
      },
      wallet,
      inventory,
      appearance: {
        selected_skin_id: selectedSkinId,
        owned_skin_ids: accountProfile.profile.owned_skin_ids,
        owned_skins: accountProfile.profile.owned_skins,
      },
      settings: accountProfile.profile.settings,
    };
  }

  async updateAppearance(userId: bigint, skinId: string): Promise<PlayerSnapshotPayload> {
    await this.accountProfileService.updateAccountProfile(userId, { skin_id: skinId });
    return await this.getSnapshot(userId);
  }

  async updateSettings(userId: bigint, settings: Record<string, unknown>): Promise<PlayerSnapshotPayload> {
    await this.accountProfileService.updateAccountProfile(userId, { settings });
    return await this.getSnapshot(userId);
  }

  async updateProfileAssets(userId: bigint, update: UpdatePlayerProfileAssetsDto): Promise<PlayerSnapshotPayload> {
    await this.accountProfileService.updateAccountProfile(userId, update);
    return await this.getSnapshot(userId);
  }
}
