import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ApiService } from './api.service';
import { Course, CourseDetails, ResourceType } from '../models/types';

const INT_TO_TYPE: Record<number, ResourceType> = { 0: 'Url', 1: 'Video', 2: 'Text', 3: 'File' };

function normalizeType(r: any) {
  return { ...r, type: typeof r.type === 'number' ? (INT_TO_TYPE[r.type] ?? 'Url') : r.type };
}

@Injectable({
  providedIn: 'root'
})
export class CourseService {
  private readonly api = inject(ApiService);

  getCourses(search?: string): Observable<Course[]> {
    const params = search ? { search } : undefined;
    return this.api.get<Course[]>('/api/courses', params);
  }

  getCourseById(id: string): Observable<CourseDetails> {
    return this.api.get<any>(`/api/courses/${id}`).pipe(
      map(c => ({
        ...c,
        topics: (c.topics ?? []).map((t: any) => ({
          ...t,
          resources: (t.resources ?? []).map(normalizeType)
        }))
      }))
    );
  }

  createCourse(title: string, description: string, creatorId: string): Observable<Course> {
    return this.api.post<Course>('/api/courses', { title, description, creatorId });
  }

  updateCourse(id: string, title: string, description: string): Observable<Course> {
    return this.api.put<Course>(`/api/courses/${id}`, { id, title, description });
  }

  publishCourse(id: string): Observable<Course> {
    return this.api.patch<Course>(`/api/courses/${id}/publish`, {});
  }

  deleteCourse(id: string): Observable<void> {
    return this.api.delete<void>(`/api/courses/${id}`);
  }

  getMyCourses(userId: string): Observable<Course[]> {
    return this.api.get<Course[]>(`/api/users/${userId}/courses`);
  }
}
