using Elwig.Models.Entities;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Elwig.Models.Dtos {
    public class MemberDeliveryData : DataTable<MemberDeliveryRow> {

        private static readonly (string, string, string?, int?)[] FieldNames = [
          ("MgNr", "MgNr.", null, 12),
            ("Name1", "Name", null, 40),
            ("Name2", "Vorname", null, 40),
            ("Address", "Adresse", null, 60),
            ("Plz", "PLZ", null, 10),
            ("Locality", "Ort", null, 60),
            ("Weight", "Geliefert", "kg", 22),
        ];

        public MemberDeliveryData(IEnumerable<MemberDeliveryRow> rows, List<string> filterNames) :
            base("Liefermengen Gesamt", "Liefermengen pro Mitglied", string.Join(" / ", filterNames), rows, FieldNames) {
        }

        public static async Task<MemberDeliveryData> FromQuery(IQueryable<DeliveryPart> query, List<string> filterNames) {
            return new((await query
                .GroupBy(p => new {
                    p.Delivery.MgNr,
                    p.Delivery.Member.Name,
                    p.Delivery.Member.GivenName,
                    p.Delivery.Member.Address,
                    p.Delivery.Member.PostalDest.AtPlz!.Plz,
                    Ort = p.Delivery.Member.PostalDest.AtPlz!.Ort.Name,
                })
                .Select(g => new {
                    g.Key,
                    Weight = g.Sum(p => p.Weight),
                }).ToListAsync())
                .Select(g => new MemberDeliveryRow {
                    MgNr = g.Key.MgNr,
                    Name1 = g.Key.Name,
                    Name2 = g.Key.GivenName,
                    Address = g.Key.Address,
                    Plz = g.Key.Plz,
                    Locality = g.Key.Ort,
                    Weight = g.Weight,
                }), filterNames);
        }
    }

    public class MemberDeliveryRow {
        public required int MgNr;
        public required string Name1;
        public required string? Name2;
        public required string Address;
        public required int Plz;
        public required string Locality;
        public required int Weight;
    }
}
