import { Inject, Injectable } from '@nestjs/common';
import { PlayerAssets, PlayerAssetType as CorePlayerAssetType } from '../../core/db/player_assets/player_assets.entity';
import { PlayerAsset, PlayerAssetType, PlayerInventoryPayload } from './player.types';

interface IPlayerAssetsService {
  grantAsset(userId: bigint, assetType: CorePlayerAssetType, assetId: string, source?: string, metadata?: Record<string, unknown>): Promise<PlayerAssets>;
  hasAsset(userId: bigint, assetType: CorePlayerAssetType, assetId: string): Promise<boolean>;
  listAssets(userId: bigint, assetType?: CorePlayerAssetType): Promise<PlayerAssets[]>;
  listAssetIds(userId: bigint, assetType: CorePlayerAssetType): Promise<string[]>;
}

@Injectable()
export class InventoryService {
  constructor(
    @Inject('IPlayerAssetsService') private readonly playerAssetsService: IPlayerAssetsService,
  ) {}

  async listInventory(userId: bigint, assetType?: PlayerAssetType): Promise<PlayerInventoryPayload> {
    const [skinIds, roomDecorIds] = await Promise.all([
      assetType && assetType !== 'skin' ? Promise.resolve([]) : this.playerAssetsService.listAssetIds(userId, 'skin'),
      assetType && assetType !== 'room_decor' ? Promise.resolve([]) : this.playerAssetsService.listAssetIds(userId, 'room_decor'),
    ]);

    const rows = await this.playerAssetsService.listAssets(userId, assetType as CorePlayerAssetType | undefined);
    const assets: PlayerAsset[] = rows.map((row) => ({
      asset_type: row.asset_type,
      asset_id: row.asset_id,
      source: row.source,
    }));

    return {
      assets,
      skin_ids: skinIds,
      room_decor_ids: roomDecorIds,
    };
  }

  async hasAsset(userId: bigint, assetType: PlayerAssetType, assetId: string): Promise<boolean> {
    return await this.playerAssetsService.hasAsset(userId, assetType, assetId);
  }

  async grantAsset(userId: bigint, assetType: PlayerAssetType, assetId: string, source = 'system'): Promise<PlayerAsset> {
    await this.playerAssetsService.grantAsset(userId, assetType, assetId, source);
    return {
      asset_type: assetType,
      asset_id: assetId,
      source,
    };
  }
}
