using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Admin.Channel.List.Create;

public sealed class Handler(IAppDbContext db) : ICommandHandler<Command, int>
{
    public async Task<int> Handle(Command request, CancellationToken ct)
    {
        var exists = await db.Channel.AnyAsync(c => c.SID == request.SID, ct);
        if (exists)
        {
            throw new Exception("이미 등록된 채널 SID입니다.");
        }

        var channel = Domain.Entities.Members.Channel.Create(
            request.MemberID,
            request.SID,
            request.Name,
            request.YouTubeUrl
        );

        channel.Update(
            request.Name,
            request.Handle,
            request.YouTubeUrl,
            request.PlatformFeeRate,
            request.IsVerified,
            request.IsActive
        );

        await db.Channel.AddAsync(channel, ct);
        await db.SaveChangesAsync(ct);

        return channel.ID;
    }
}