import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })  
export class AllapiService {
  private apiUrl = 'https://infoways.in/funtelapi/addstory.php';
  private logoutUrl = 'https://infoways.in/funtelapi/logout.php';
  private userStory = 'https://infoways.in/funtelapi/allstory.php';
  private createStoryApi = 'https://infoways.in/funtelapi/createstory.php';

  constructor(private http: HttpClient) {} 

 addStory(formData: FormData): Observable<any> {
  

  return this.http.post(this.apiUrl, formData, {
   
    withCredentials: true 
  });
}

createStory(formData: FormData): Observable<any> {
 

  return this.http.post(this.createStoryApi, formData, {
   
    withCredentials: true
  });
}
  

private getFresh<T>(url: string): Observable<T> {
  const timestamp = new Date().getTime();
  const freshUrl = `${url}${url.includes('?') ? '&' : '?'}_=${timestamp}`;
  
  return this.http.get<T>(freshUrl, {
    withCredentials: true,
    headers: {
      'content-type': 'application/json',
    }
  });
}

  getUserStories(userId: number): Observable<any> {
  const timestamp = new Date().getTime();
  const url = `${this.userStory}?user_id=${userId}&_=${timestamp}`;

  const headers = new HttpHeaders({
    'content-type': 'application/json',
  });

  return this.http.get<any>(url, {
    headers: headers,
    withCredentials: true
  }).pipe(
    catchError(error => {
      console.error('Error fetching user stories:', error);
      return throwError(() => new Error('Failed to fetch user stories'));
    })
  );
}
uploadVideo(formData: FormData) {
  return this.http.post('https://infoways.in/funtelapi/upload_video.php', formData, {
    reportProgress: true,
    observe: 'events'
  });
}
getStoryById(storyId: number): Observable<any> {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
     
    });

    return this.http.get<any>(
      `https://infoways.in/funtelapi/getstory.php?id=${storyId}`,
      { 
        headers: headers,
        withCredentials: true 
      }
    ).pipe(
      catchError(error => {
        console.error('Error fetching story:', error);
        return throwError(() => new Error('Failed to fetch story'));
      })
    );
  }
  publishStory(formData: FormData) {
  return this.http.post<any>('https://infoways.in/funtelapi/publish_story.php', formData, {
    withCredentials: true
  });
}
  
  
 updateStory(formData: FormData): Observable<any> {
  console.log('Service sending:', {
    storyId: formData.get('story_id'),
    title: formData.get('story_title'),
    content: formData.get('story_content'),
    videoLink: formData.get('video_link'),
    audioLink: formData.get('audio')
  });
  return this.http.post<any>('https://infoways.in/funtelapi/updatestory.php', formData,{
    withCredentials: true
  });
}

  

  
}
