import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../core/contracts/library.dart';
import '../core/domain/ports/emby_gateway.dart';
import 'di_providers.dart';
import 'session_provider.dart';


final personItemsProvider = FutureProvider.family<List<EmbyRawItem>, String>((
  ref,
  embyPersonId,
) async {
  if (embyPersonId.isEmpty) return const <EmbyRawItem>[];

  final session = ref.watch(activeSessionProvider);
  if (session == null) return const <EmbyRawItem>[];

  final gateway = await ref.read(embyGatewayProvider.future);
  final ctx = AuthedRequestContext(
    baseUrl: session.serverUrl,
    token: session.token,
    userId: session.userId,
  );

  return gateway.getLibraryItems(
    ctx: ctx,
    personIds: [embyPersonId],
    includeItemTypes: 'Movie,Series',
    recursive: true,
    sortBy: 'ProductionYear,SortName',
    sortOrder: SortOrder.descending,
    limit: 200,
    fields:
        'BasicSyncInfo,PrimaryImageAspectRatio,CommunityRating,ProductionYear,UserData',
  );
});


final embyPersonIdByNameProvider = FutureProvider.family<String?, String>((
  ref,
  name,
) async {
  final trimmed = name.trim();
  if (trimmed.isEmpty) return null;

  final session = ref.watch(activeSessionProvider);
  if (session == null) return null;

  final gateway = await ref.read(embyGatewayProvider.future);
  final ctx = AuthedRequestContext(
    baseUrl: session.serverUrl,
    token: session.token,
    userId: session.userId,
  );

  final items = await gateway.getLibraryItems(
    ctx: ctx,
    includeItemTypes: 'Person',
    searchTerm: trimmed,
    recursive: true,
    limit: 5,
    fields: 'BasicSyncInfo',
  );
  if (items.isEmpty) return null;

  final lower = trimmed.toLowerCase();
  final exact = items.where((e) => e.Name.toLowerCase() == lower);
  final match = exact.isNotEmpty ? exact.first : items.first;
  return match.Id;
});


final personItemDetailProvider = FutureProvider.family<EmbyRawItem?, String>((
  ref,
  embyPersonId,
) async {
  if (embyPersonId.isEmpty) return null;

  final session = ref.watch(activeSessionProvider);
  if (session == null) return null;

  final gateway = await ref.read(embyGatewayProvider.future);
  final ctx = AuthedRequestContext(
    baseUrl: session.serverUrl,
    token: session.token,
    userId: session.userId,
  );

  try {
    return await gateway.getItemDetail(ctx, embyPersonId);
  } catch (_) {
    return null;
  }
});
