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

namespace ClaudeDo.Data.Repositories;

public sealed class TagRepository
{
    private readonly ClaudeDoDbContext _context;

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

    public async Task<List<TagEntity>> GetAllAsync(CancellationToken ct = default)
    {
        return await _context.Tags.OrderBy(t => t.Id).ToListAsync(ct);
    }

    public async Task<long> GetOrCreateAsync(string name, CancellationToken ct = default)
    {
        var existing = await _context.Tags.FirstOrDefaultAsync(t => t.Name == name, ct);
        if (existing is not null)
            return existing.Id;

        var tag = new TagEntity { Name = name };
        _context.Tags.Add(tag);
        await _context.SaveChangesAsync(ct);
        return tag.Id;
    }
}
