"""Company-facing view of its own drivers' earnings and orders — the same
underlying data as market/earnings.py's picker-scoped ledger and the admin
financial dashboard, just filtered down to one company's driver_ids instead
of read platform-wide. No new schema; a company sees, it doesn't authorize —
payout stays admin-only (market/earnings.py::pay_out_picker)."""

from decimal import Decimal

from accounts.supabase_client import get_client


def get_company_earnings_summary(driver_ids):
    """{pending_amount, pending_count, paid_amount, lifetime_amount} across
    every one of the company's drivers — same shape as
    earnings.get_picker_earnings_summary, just summed over a group."""
    driver_ids = list(driver_ids)
    if not driver_ids:
        return {'pending_amount': Decimal('0'), 'pending_count': 0, 'paid_amount': Decimal('0'), 'lifetime_amount': Decimal('0')}
    rows = get_client().table('pickker_picker_earnings').select('*').in_('picker_id', driver_ids).execute().data
    pending = sum((Decimal(str(r['amount'])) for r in rows if r['status'] == 'pending'), Decimal('0'))
    paid = sum((Decimal(str(r['amount'])) for r in rows if r['status'] == 'paid'), Decimal('0'))
    return {
        'pending_amount': pending,
        'pending_count': sum(1 for r in rows if r['status'] == 'pending'),
        'paid_amount': paid,
        'lifetime_amount': pending + paid,
    }


def get_company_earnings_by_driver(driver_ids):
    """Per-driver breakdown, sorted by who's owed the most — mirrors
    earnings.get_all_pickers_earnings_overview's shape, scoped to this
    company's drivers only."""
    driver_ids = list(driver_ids)
    if not driver_ids:
        return []
    client = get_client()
    earnings = client.table('pickker_picker_earnings').select('*').in_('picker_id', driver_ids).execute().data
    by_driver = {}
    for e in earnings:
        by_driver.setdefault(e['picker_id'], []).append(e)

    users_by_id = {
        u['id']: u for u in
        client.table('pickker_users').select('id, first_name, last_name').in_('id', driver_ids).execute().data
    }

    overview = []
    for driver_id in driver_ids:
        rows = by_driver.get(driver_id, [])
        user = users_by_id.get(driver_id)
        pending = sum((Decimal(str(r['amount'])) for r in rows if r['status'] == 'pending'), Decimal('0'))
        paid = sum((Decimal(str(r['amount'])) for r in rows if r['status'] == 'paid'), Decimal('0'))
        overview.append({
            'driver_id': driver_id,
            'name': f"{user['first_name']} {user['last_name']}".strip() if user else 'Unknown',
            'pending_amount': pending,
            'pending_count': sum(1 for r in rows if r['status'] == 'pending'),
            'paid_amount': paid,
        })
    overview.sort(key=lambda o: o['pending_amount'], reverse=True)
    return overview


def get_company_orders(driver_ids, limit=50):
    """Orders across every one of the company's drivers, most recent first —
    the raw pickker_orders rows already carry the fee breakdown
    (delivery_fee/picking_fee/package_fee/total_amount) needed for a
    financial view without joining the earnings ledger."""
    driver_ids = list(driver_ids)
    if not driver_ids:
        return []
    return (
        get_client()
        .table('pickker_orders')
        .select('id, picker_id, status, delivery_date, items_subtotal, delivery_fee, picking_fee, package_fee, total_amount, created_at, account_type, payment_released_at')
        .in_('picker_id', driver_ids)
        .order('created_at', desc=True)
        .limit(limit)
        .execute()
        .data
    )
