using System.Text.Json;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using DorkNet.Server.Auth;
using DorkNet.Server.Data;
using DorkNet.Server.Data.Entities;
namespace DorkNet.Server.Controllers.API.RoomEarningsDistributions;
///
/// Co-owner earnings-split configuration for a room. NOT gross-earnings
/// totals — this is how a room's token earnings are divided among its
/// co-owners. Client contract (RecNet.Runtime HPEBLAHNBLC / FEJOMKJBOOE):
///
/// GET api/roomEarningsDistributions/v1/earningsDistribution/{roomId}
/// → a SINGLE object { RoomId, EarningsDistributionMapping:
/// Dictionary<accountId,percent>, EarningsDistributionMethod: 0|1 }
/// (0 = Equal, 1 = Custom).
/// POST the bare .../v1/earningsDistribution with that object
/// to save.
///
/// Persisted as JSON on the room creator's settings row, keyed per room.
///
[ApiController]
[Authorize]
public class RoomEarningsDistributionsController(DorkNetDbContext db) : ControllerBase
{
private const int MethodEqual = 0;
private const int MethodCustom = 1;
private static string SettingKey(long roomId) => $"room:earningsdist:{roomId}";
/// GET the split config for one room (client's per-room GET).
[HttpGet("api/roomEarningsDistributions/v1/earningsDistribution/{roomId:long}")]
public async Task GetDistribution(long roomId)
{
var room = await db.Rooms.FirstOrDefaultAsync(r => r.Id == roomId);
if (room is null) return NotFound();
var (method, mapping) = await LoadAsync(room.CreatorPlayerId, roomId, room.CreatorPlayerId);
return Ok(BuildDto(roomId, method, mapping));
}
/// Bare-URL GET kept for compatibility: returns the caller's
/// own rooms' split configs as a list. The 2023 client doesn't hit this
/// (it GETs the per-room path above), but tooling may.
[HttpGet("api/roomEarningsDistributions")]
[HttpGet("api/roomEarningsDistributions/v1/earningsDistribution")]
public async Task ListMine([FromQuery] long? roomId = null)
{
var me = this.RequireCurrentPlayerId();
var q = db.Rooms.Where(r => r.CreatorPlayerId == me);
if (roomId is long rid && rid > 0) q = q.Where(r => r.Id == rid);
var rooms = await q.Select(r => new { r.Id, r.CreatorPlayerId }).ToListAsync();
var result = new List