import { axiosInstance } from './axios';
import type { Asset, Organization, Vertical, TaxonomyMeta, AssetQueryFilters } from '../types/assets';

export const getAssets = async (filters?: AssetQueryFilters): Promise<Asset[]> => {
  const params: Record<string, string> = {};
  if (filters?.search) params.search = filters.search;
  if (filters?.verticalIds?.length) params.verticalIds = filters.verticalIds.join(',');
  if (filters?.contentTypes?.length) params.contentTypes = filters.contentTypes.join(',');
  if (filters?.subcategories?.length) params.subcategories = filters.subcategories.join(',');
  if (filters?.tags?.length) params.tags = filters.tags.join(',');
  if (filters?.sortBy) params.sortBy = filters.sortBy;

  const response = await axiosInstance.get<Asset[]>('/assets', { params });
  return response.data;
};

export const getOrganizations = async (): Promise<Organization[]> => {
  const response = await axiosInstance.get<Organization[]>('/organizations');
  return response.data;
};

export const uploadAsset = async (formData: FormData): Promise<void> => {
  await axiosInstance.post('/assets/upload', formData, {
    headers: { 'Content-Type': 'multipart/form-data' }
  });
};

export const updateAsset = async (
  id: string,
  payload: {
    title?: string;
    description?: string;
    categoryId?: string;
    subcategory?: string;
    verticalIds?: string[];
    tags?: string[];
    githubUrl?: string;
    isDownloadable?: boolean;
    shares?: Array<{ organizationId: string; userId: string | null }>;
  }
): Promise<void> => {
  await axiosInstance.patch(`/assets/${id}`, payload);
};

export const deleteAsset = async (id: string): Promise<void> => {
  await axiosInstance.delete(`/assets/${id}`);
};

export const requestDownload = async (id: string): Promise<void> => {
  await axiosInstance.post(`/assets/${id}/request-download`);
};

export const approveDownloadRequest = async (assetId: string, requestId: string): Promise<void> => {
  await axiosInstance.post(`/assets/${assetId}/approve-download/${requestId}`);
};

export const rejectDownloadRequest = async (assetId: string, requestId: string): Promise<void> => {
  await axiosInstance.post(`/assets/${assetId}/reject-download/${requestId}`);
};

export const downloadAssetFile = async (id: string): Promise<void> => {
  await axiosInstance.post(`/assets/${id}/download`);
};

export const bulkShareAssets = async (
  assetIds: string[],
  shares: Array<{ organizationId: string; userId: string | null }>
): Promise<void> => {
  await axiosInstance.patch('/assets/bulk-share', { assetIds, shares });
};

export interface AssetGroup {
  id: string;
  name: string;
  description: string | null;
  assets: Asset[];
  createdAt: string;
  updatedAt: string;
}

export const getAssetGroups = async (): Promise<AssetGroup[]> => {
  const response = await axiosInstance.get<AssetGroup[]>('/assets/groups/list');
  return response.data;
};

export const createAssetGroup = async (payload: { name: string; description?: string; assetIds?: string[] }): Promise<AssetGroup> => {
  const response = await axiosInstance.post<AssetGroup>('/assets/groups/create', payload);
  return response.data;
};

export const deleteAssetGroup = async (id: string): Promise<void> => {
  await axiosInstance.delete(`/assets/groups/${id}`);
};

export const addAssetsToGroup = async (groupId: string, assetIds: string[]): Promise<void> => {
  await axiosInstance.patch(`/assets/groups/${groupId}/add-assets`, { assetIds });
};

export const removeAssetsFromGroup = async (groupId: string, assetIds: string[]): Promise<void> => {
  await axiosInstance.patch(`/assets/groups/${groupId}/remove-assets`, { assetIds });
};

export interface ScrapedCaseStudy {
  title: string;
  thumbnailUrl: string;
  problemStatement: string;
  solution: string;
}

export const scrapeCaseStudy = async (url: string): Promise<ScrapedCaseStudy> => {
  const response = await axiosInstance.get<ScrapedCaseStudy>('/assets/scrape-case-study', {
    params: { url }
  });
  return response.data;
};

// Taxonomy API
export const getVerticals = async (): Promise<Vertical[]> => {
  const response = await axiosInstance.get<Vertical[]>('/taxonomy/verticals');
  return response.data;
};

export const getTaxonomyMeta = async (): Promise<TaxonomyMeta> => {
  const response = await axiosInstance.get<TaxonomyMeta>('/taxonomy/meta');
  return response.data;
};

export const createVertical = async (payload: { name: string; icon?: string; description?: string; color?: string }): Promise<Vertical> => {
  const response = await axiosInstance.post<Vertical>('/taxonomy/verticals', payload);
  return response.data;
};

export const updateVertical = async (id: string, payload: Partial<Vertical>): Promise<Vertical> => {
  const response = await axiosInstance.put<Vertical>(`/taxonomy/verticals/${id}`, payload);
  return response.data;
};

export const deleteVertical = async (id: string): Promise<void> => {
  await axiosInstance.delete(`/taxonomy/verticals/${id}`);
};

// Notification API
export const sendAssetAnnouncement = async (payload: { title: string; message: string; targetOrgIds?: string[]; assetIds?: string[] }): Promise<void> => {
  await axiosInstance.post('/assets/notify', payload);
};

