import axios from '../utils/api';
import { Author } from '../types/auth';

interface AuthorFormData {
  displayName: string;
  bio?: string;
  avatarUrl?: string;
  email?: string;
  order?: number;
  twitterUrl?: string;
  instagramUrl?: string;
  websiteUrl?: string;
  isActive?: boolean;
}

export interface AuthorsResponse {
  authors: Author[];
  totalPages: number,
  currentPage: number,
  total: number;
}

export const authorService = {
  getAuthors: async (role: string, page: number): Promise<AuthorsResponse> => {
    try {
      const response = await axios.get('/authors', {
        params: {
          role: role || undefined, // не отправлять параметр если пусто
          page: page || 1,
        },
      });

      return response.data;
    } catch (error) {
      console.error('Ошибка получения списка авторов:', error);
      throw new Error('Невозможно получить список авторов');
    }
  },

  createAuthor: async (authorData: AuthorFormData): Promise<Author> => {
    try {
      const response = await axios.post('/authors', authorData);
      return response.data;
    } catch (error) {
      console.error('Ошибка создания автора:', error);
      throw new Error('Невозможно создать автора');
    }
  },

  updateAuthor: async (authorId: string, authorData: Partial<AuthorFormData>): Promise<Author> => {
    try {
      const response = await axios.put(`/authors/${authorId}`, authorData);
      return response.data;
    } catch (error) {
      console.error('Ошибка изменения данных автора:', error);
      throw new Error('Невозможно изменить данные автора');
    }
  },

  deleteAuthor: async (authorId: string): Promise<void> => {
    try {
      await axios.delete(`/authors/${authorId}`);
    } catch (error) {
      console.error('Error deleting author:', error);
      throw new Error('Failed to delete author');
    }
  },

  reorderAuthor: async (authorId: string, direction: 'up' | 'down') => {
    await axios.put(`/authors/${authorId}/reorder`, { direction });
  },

  toggleActive: async (authorId: string, isActive: boolean): Promise<Author> => {
    try {
      const response = await axios.put(`/authors/${authorId}/toggle-active`, { isActive });
      return response.data;
    } catch (error) {
      console.error('Error toggling author status:', error);
      throw new Error('Failed to toggle author status');
    }
  },

  linkUser: async (authorId: string, userId: string): Promise<void> => {
    try {
      await axios.put(`/authors/${authorId}/link-user`, { userId });
    } catch (error) {
      console.error('Error linking user to author:', error);
      throw new Error('Failed to link user to author');
    }
  },

  unlinkUser: async (authorId: string): Promise<void> => {
    try {
      await axios.put(`/authors/${authorId}/unlink-user`);
    } catch (error) {
      console.error('Error unlinking user from author:', error);
      throw new Error('Failed to unlink user from author');
    }
  }
};