using ClaudeDo.Data.Models;
using Microsoft.EntityFrameworkCore;

namespace ClaudeDo.Data.Repositories;

public sealed class AppSettingsRepository
{
    private readonly ClaudeDoDbContext _context;

    public AppSettingsRepository(ClaudeDoDbContext context) => _context = context;

    public async Task<AppSettingsEntity> GetAsync(CancellationToken ct = default)
    {
        var row = await _context.AppSettings.AsNoTracking()
            .FirstOrDefaultAsync(s => s.Id == AppSettingsEntity.SingletonId, ct);
        if (row is not null) return row;

        row = new AppSettingsEntity { Id = AppSettingsEntity.SingletonId };
        _context.AppSettings.Add(row);
        await _context.SaveChangesAsync(ct);
        _context.Entry(row).State = EntityState.Detached;
        return row;
    }

    public async Task UpdateAsync(AppSettingsEntity updated, CancellationToken ct = default)
    {
        var row = await _context.AppSettings
            .FirstOrDefaultAsync(s => s.Id == AppSettingsEntity.SingletonId, ct);
        if (row is null)
        {
            row = new AppSettingsEntity { Id = AppSettingsEntity.SingletonId };
            _context.AppSettings.Add(row);
        }

        row.DefaultClaudeInstructions = updated.DefaultClaudeInstructions ?? string.Empty;
        row.DefaultModel = string.IsNullOrWhiteSpace(updated.DefaultModel) ? "sonnet" : updated.DefaultModel;
        row.DefaultMaxTurns = updated.DefaultMaxTurns;
        row.DefaultPermissionMode = string.IsNullOrWhiteSpace(updated.DefaultPermissionMode)
            ? "bypassPermissions" : updated.DefaultPermissionMode;
        row.WorktreeStrategy = string.IsNullOrWhiteSpace(updated.WorktreeStrategy) ? "sibling" : updated.WorktreeStrategy;
        row.CentralWorktreeRoot = string.IsNullOrWhiteSpace(updated.CentralWorktreeRoot)
            ? null : updated.CentralWorktreeRoot;
        row.WorktreeAutoCleanupEnabled = updated.WorktreeAutoCleanupEnabled;
        row.WorktreeAutoCleanupDays = updated.WorktreeAutoCleanupDays;

        await _context.SaveChangesAsync(ct);
    }
}
