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

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

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

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

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

  getResources(): Observable<Resource[]> {
    return this.api.get<any[]>('/api/resources').pipe(
      map(list => list.map(normalizeResource))
    );
  }

  createResource(type: ResourceType, title: string, content: string): Observable<Resource> {
    return this.api.post<any>('/api/resources', { type: TYPE_TO_INT[type], title, content }).pipe(
      map(normalizeResource)
    );
  }

  updateResource(id: string, type: ResourceType, title: string, content: string): Observable<Resource> {
    return this.api.put<any>(`/api/resources/${id}`, { id, type: TYPE_TO_INT[type], title, content }).pipe(
      map(normalizeResource)
    );
  }

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