import { Storage } from '../../shared/providers/storage';
import { SavedFiltersProvider } from '../providers/saved-filters.provider';
import type { SavedFilterResolvers } from './../../../__generated__/types';

export const SavedFilter: SavedFilterResolvers = {
  id: filter => filter.id,
  name: filter => filter.name,
  description: filter => filter.description,
  filters: filter => {
    const filters = filter.filters as {
      operationHashes?: string[];
      clientFilters?: Array<{ name: string; versions?: string[] | null }>;
      dateRange?: { from: string; to: string } | null;
      excludeOperations?: boolean;
      excludeClientFilters?: boolean;
    };
    return {
      operationHashes: filters.operationHashes ?? [],
      clientFilters:
        filters.clientFilters?.map(cf => ({
          name: cf.name,
          versions: cf.versions ?? null,
        })) ?? [],
      dateRange: filters.dateRange ?? null,
      excludeOperations: filters.excludeOperations ?? false,
      excludeClientFilters: filters.excludeClientFilters ?? false,
    };
  },
  visibility: filter => (filter.visibility === 'private' ? 'PRIVATE' : 'SHARED'),
  viewsCount: filter => filter.viewsCount,
  createdAt: filter => filter.createdAt,
  updatedAt: filter => filter.updatedAt,
  createdBy: async (filter, _args, { injector }) => {
    return injector.get(Storage).getUserById({ id: filter.createdByUserId });
  },
  updatedBy: async (filter, _args, { injector }) => {
    if (!filter.updatedByUserId) {
      return null;
    }
    return injector.get(Storage).getUserById({ id: filter.updatedByUserId });
  },
  viewerCanUpdate: async (filter, _args, { injector, session }) => {
    // For shared filters, check sharedSavedFilter:modify permission
    if (filter.visibility === 'shared' && filter.orgId) {
      const canModifyShared = await session.canPerformAction({
        action: 'sharedSavedFilter:modify',
        organizationId: filter.orgId,
        params: { organizationId: filter.orgId, projectId: filter.projectId },
      });
      if (!canModifyShared) return false;
    }
    // Check ownership (private filters can only be modified by creator)
    const currentUser = await session.getViewer();
    return injector.get(SavedFiltersProvider).canUserModifyFilter(filter, currentUser.id);
  },
  viewerCanDelete: async (filter, _args, { injector, session }) => {
    // For shared filters, check sharedSavedFilter:modify permission
    if (filter.visibility === 'shared' && filter.orgId) {
      const canModifyShared = await session.canPerformAction({
        action: 'sharedSavedFilter:modify',
        organizationId: filter.orgId,
        params: { organizationId: filter.orgId, projectId: filter.projectId },
      });
      if (!canModifyShared) return false;
    }
    // Check ownership (private filters can only be modified by creator)
    const currentUser = await session.getViewer();
    return injector.get(SavedFiltersProvider).canUserDeleteFilter(filter, currentUser.id);
  },
};
