using AuthorBuddy.Web.Data;
using AuthorBuddy.Web.Models;
using Microsoft.EntityFrameworkCore;

namespace AuthorBuddy.Web.Services;

public class ProjectService : IProjectService
{
    private readonly IDbContextFactory<AppDbContext> _contextFactory;
    private readonly IFileScannerService _fileScannerService;

    public ProjectService(IDbContextFactory<AppDbContext> contextFactory, IFileScannerService fileScannerService)
    {
        _contextFactory = contextFactory;
        _fileScannerService = fileScannerService;
    }

    public async Task<int> CreateNewProjectAsync(string projectName, string rootPath)
    {
        string[] subFolders = { "00_Drafts", "01_Fakten", "02_Characters", "03_Archive" };
        foreach (var subFolder in subFolders)
        {
            Directory.CreateDirectory(Path.Combine(rootPath, subFolder));
        }

        string readmePath = Path.Combine(rootPath, "00_Projekt_Info.md");
        await File.WriteAllTextAsync(readmePath, $"# Projekt: {projectName}\nErstellt am: {DateTime.Now}");

        await using var context = await _contextFactory.CreateDbContextAsync();

        var entity = new ProjectEntity
        {
            Name = projectName,
            RootPath = rootPath,
            LastOpened = DateTime.Now
        };

        context.Projects.Add(entity);
        await context.SaveChangesAsync();

        return entity.Id;
    }

    public async Task<List<Project>> GetAllProjectsAsync()
    {
        await using var context = await _contextFactory.CreateDbContextAsync();

        return await context.Projects
            .OrderByDescending(p => p.LastOpened)
            .Select(p => new Project
            {
                Id = p.Id,
                Name = p.Name,
                RootPath = p.RootPath
            })
            .ToListAsync();
    }

    public async Task SyncProjectFilesAsync(int projectId, string directoryPath, IProgress<string> progress)
    {
        await _fileScannerService.ScanProjectFolderAsync(projectId, directoryPath, progress);
    }
}
