"""Chat between a fleet company and one of its own drivers — not tied to any
particular order, unlike market/messaging.py's customer<->picker threads
(a company needs to reach a driver between deliveries too). Sibling module,
same shape as market/messaging.py, keyed by (company_id, driver_id) instead
of order_id."""

from concurrent.futures import ThreadPoolExecutor

from accounts.supabase_client import get_client


def get_fleet_messages(company_id, driver_id):
    return (
        get_client()
        .table('pickker_fleet_messages')
        .select('*')
        .eq('company_id', company_id)
        .eq('driver_id', driver_id)
        .order('created_at')
        .execute()
        .data
    )


def send_fleet_message(company_id, driver_id, sender_id, message):
    message = (message or '').strip()
    if not message:
        return None
    resp = get_client().table('pickker_fleet_messages').insert({
        'company_id': company_id,
        'driver_id': driver_id,
        'sender_id': sender_id,
        'message': message[:1000],
    }).execute()
    return resp.data[0] if resp.data else None


def mark_fleet_messages_seen(user_id, company_id, driver_id):
    client = get_client()
    latest = (
        client.table('pickker_fleet_messages')
        .select('id')
        .eq('company_id', company_id)
        .eq('driver_id', driver_id)
        .order('id', desc=True)
        .limit(1)
        .execute()
        .data
    )
    if not latest:
        return
    last_id = latest[0]['id']
    existing = (
        client.table('pickker_fleet_message_reads')
        .select('id')
        .eq('user_id', user_id).eq('company_id', company_id).eq('driver_id', driver_id)
        .execute()
    )
    if existing.data:
        client.table('pickker_fleet_message_reads').update({'last_seen_message_id': last_id}).eq('id', existing.data[0]['id']).execute()
    else:
        client.table('pickker_fleet_message_reads').insert({
            'user_id': user_id, 'company_id': company_id, 'driver_id': driver_id, 'last_seen_message_id': last_id,
        }).execute()


def get_unseen_fleet_message_count(user_id, company_id, driver_ids):
    """Total unread messages (sent by someone else) across the given
    drivers' threads with this company — same parallel-fetch pattern as
    market/messaging.py::get_unseen_message_count."""
    driver_ids = list(driver_ids)
    if not driver_ids:
        return 0
    client = get_client()

    def _fetch_reads():
        return (
            client.table('pickker_fleet_message_reads')
            .select('driver_id, last_seen_message_id')
            .eq('user_id', user_id).eq('company_id', company_id)
            .in_('driver_id', driver_ids)
            .execute()
            .data
        )

    def _fetch_messages():
        return (
            client.table('pickker_fleet_messages')
            .select('id, driver_id, sender_id')
            .eq('company_id', company_id)
            .in_('driver_id', driver_ids)
            .neq('sender_id', user_id)
            .execute()
            .data
        )

    with ThreadPoolExecutor(max_workers=2) as executor:
        reads_future = executor.submit(_fetch_reads)
        messages_future = executor.submit(_fetch_messages)
        reads = reads_future.result()
        messages = messages_future.result()

    last_seen_by_driver = {r['driver_id']: r['last_seen_message_id'] for r in reads}
    count = 0
    for m in messages:
        last_seen = last_seen_by_driver.get(m['driver_id'])
        if last_seen is None or m['id'] > last_seen:
            count += 1
    return count
