using ClipForge.Contracts.Requests; using ClipForge.Contracts.Responses; using ClipForge.Core.Interfaces; using ClipForge.Core.Interfaces.Services; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; namespace ClipForge.Api.Endpoints; public static class VideoEndpoints { public static void MapVideoEndpoints(this WebApplication app) { var group = app.MapGroup("/api/videos").WithTags("Videos"); group.MapPost("/assemble", async (AssembleVideoRequest request, IVideoAssemblyService service) => { var video = await service.AssembleVideoAsync(request.ScriptId); return Results.Ok(MapToResponse(video)); }); group.MapGet("/", async (IVideoAssetRepository repository) => { var videos = await repository.GetAllAsync(); return Results.Ok(videos.Select(MapToResponse)); }); group.MapGet("/{id:guid}", async (Guid id, IVideoAssetRepository repository) => { var video = await repository.GetByIdAsync(id); return video is null ? Results.NotFound() : Results.Ok(MapToResponse(video)); }); group.MapGet("/status/{status}", async (string status, IVideoAssetRepository repository) => { var videos = await repository.GetByStatusAsync(status); return Results.Ok(videos.Select(MapToResponse)); }); group.MapDelete("/{id:guid}", async (Guid id, IVideoAssetRepository repository, ClipForge.Infrastructure.Data.AppDbContext db) => { var video = await repository.GetByIdAsync(id); if (video is null) return Results.NotFound(); // Delete all related records and files var sql = $@" DELETE FROM ""PublishJobs"" WHERE ""VideoAssetId"" = '{id}'; DELETE FROM ""CaptionAssets"" WHERE ""VideoAssetId"" = '{id}'; DELETE FROM ""VoiceAssets"" WHERE ""VideoScriptId"" = '{video.VideoScriptId}'; DELETE FROM ""VideoAssets"" WHERE ""Id"" = '{id}'; DELETE FROM ""VideoScripts"" WHERE ""Id"" = '{video.VideoScriptId}'; "; await db.Database.ExecuteSqlRawAsync(sql); // Delete files from disk try { if (File.Exists(video.FilePath)) File.Delete(video.FilePath); if (File.Exists(video.ThumbnailPath)) File.Delete(video.ThumbnailPath); } catch { /* ignore file errors */ } return Results.Ok(new { Message = "Video deleted" }); }); group.MapGet("/{id:guid}/download", async (Guid id, IVideoAssetRepository repository, IWebHostEnvironment env) => { var video = await repository.GetByIdAsync(id); if (video is null) return Results.NotFound(); // Resolve path relative to content root var filePath = video.FilePath; if (filePath.StartsWith("./")) filePath = Path.Combine(env.ContentRootPath, filePath[2..]); filePath = Path.GetFullPath(filePath); if (!File.Exists(filePath)) return Results.NotFound($"File not found: {filePath}"); return Results.File(filePath, "video/mp4", $"clipforge_{id}.mp4"); }); } private static VideoAssetResponse MapToResponse(ClipForge.Core.Entities.VideoAsset video) => new( video.Id, video.VideoScriptId, video.FilePath, video.ThumbnailPath, video.Width, video.Height, video.DurationSeconds, video.FileSizeBytes, video.Format, video.Status, video.CreatedAt); }