import { injectable, unmanaged } from 'inversify';
import { Result } from '@/lib/contracts/Result';
import { Service, DomainError } from '@/lib/contracts/services/Service';
import { LeagueWalletApiDto } from '@/lib/types/tbd/LeagueWalletApiDto';
import { WalletsApiClient } from '@/lib/api/wallets/WalletsApiClient';

@injectable()
export class LeagueWalletService implements Service {
  constructor(@unmanaged() private readonly apiClient?: WalletsApiClient) {}

  async getWalletForLeague(leagueId: string): Promise<LeagueWalletApiDto> {
    if (this.apiClient) {
      const res = await this.apiClient.getLeagueWallet(leagueId);
      return ((res as any).value || res) as any;
    }
    const result = await this.getWalletData(leagueId);
    if (result.isErr()) throw new Error(result.getError().message);
    return result.unwrap();
  }

  async withdraw(
    leagueId: string,
    amount: number,
    currency: string,
    seasonId: string,
    destinationAccount: string
  ): Promise<{ success: boolean; message?: string }> {
    if (this.apiClient) {
      const res = await this.apiClient.withdrawFromLeagueWallet(leagueId, {
        amount,
        currency,
        seasonId,
        destinationAccount,
      });
      return (res as any).value || res;
    }
    // Mock implementation
    return { success: true };
  }

  async getWalletData(leagueId: string): Promise<Result<LeagueWalletApiDto, DomainError>> {
    // Mock data since backend not implemented
    const mockData: LeagueWalletApiDto = {
      leagueId,
      balance: 15750.00,
      currency: 'USD',
      transactions: [
        {
          id: 'txn-1',
          type: 'sponsorship',
          amount: 5000.00,
          description: 'Main sponsorship from Acme Racing',
          createdAt: '2024-10-01T10:00:00Z',
          status: 'completed',
        },
        {
          id: 'txn-2',
          type: 'prize',
          amount: 2500.00,
          description: 'Prize money from championship',
          createdAt: '2024-09-15T14:30:00Z',
          status: 'completed',
        },
        {
          id: 'txn-3',
          type: 'withdrawal',
          amount: -1200.00,
          description: 'Equipment purchase',
          createdAt: '2024-09-10T09:15:00Z',
          status: 'completed',
        },
        {
          id: 'txn-4',
          type: 'deposit',
          amount: 5000.00,
          description: 'Entry fees from season registration',
          createdAt: '2024-08-01T12:00:00Z',
          status: 'completed',
        },
      ],
    };
    return Result.ok(mockData);
  }
}
