import '../models/file_item.dart';
import '../models/viewer_session.dart';
import '../models/editor_session.dart';
import '../models/annotation.dart';
import '../repositories/file_repository.dart';
import 'api_client.dart';

class FileService {
  final ApiClient _apiClient;

  FileService(this._apiClient);

  Future<List<FileItem>> getFiles(String orgId, String path) async {
    if (path.isEmpty) {
      throw Exception('Path cannot be empty');
    }
    return await _apiClient.getList(
      '/orgs/$orgId/files',
      fromJson: (data) => FileItem(
        name: data['name'],
        path: data['path'],
        type: data['type'] == 'file' ? FileType.file : FileType.folder,
        size: data['size'],
        lastModified: DateTime.parse(data['lastModified']),
      ),
    );
  }

  Future<FileItem?> getFile(String orgId, String path) async {
    throw UnimplementedError();
  }

  Future<void> uploadFile(String orgId, FileItem file) async {
    throw UnimplementedError();
  }

  Future<void> deleteFile(String orgId, String path) async {
    throw UnimplementedError();
  }

  Future<void> createFolder(
    String orgId,
    String parentPath,
    String folderName,
  ) async {
    throw UnimplementedError();
  }

  Future<void> moveFile(
    String orgId,
    String sourcePath,
    String targetPath,
  ) async {
    throw UnimplementedError();
  }

  Future<void> renameFile(String orgId, String path, String newName) async {
    throw UnimplementedError();
  }

  Future<List<FileItem>> searchFiles(String orgId, String query) async {
    throw UnimplementedError();
  }

  Future<ViewerSession> requestViewerSession(
    String orgId,
    String fileId,
  ) async {
    if (orgId.isEmpty || fileId.isEmpty) {
      throw Exception('OrgId and fileId cannot be empty');
    }
    return await _apiClient.get(
      '/orgs/$orgId/files/$fileId/view',
      fromJson: (data) => ViewerSession.fromJson(data),
    );
  }

  Future<EditorSession> requestEditorSession(
    String orgId,
    String fileId,
  ) async {
    if (orgId.isEmpty || fileId.isEmpty) {
      throw Exception('OrgId and fileId cannot be empty');
    }
    return await _apiClient.get(
      '/orgs/$orgId/files/$fileId/edit',
      fromJson: (data) => EditorSession.fromJson(data),
    );
  }

  Future<void> saveAnnotations(
    String orgId,
    String fileId,
    List<Annotation> annotations,
  ) async {
    if (orgId.isEmpty || fileId.isEmpty) {
      throw Exception('OrgId and fileId cannot be empty');
    }
    await _apiClient.post(
      '/orgs/$orgId/files/$fileId/annotations',
      data: {
        'annotations': annotations.map((a) => a.toJson()).toList(),
        'baseVersionId': '1', // mock
      },
      fromJson: (data) => null,
    );
  }
}
