"""Exercise staff and customer actions using a disposable Laravel installation."""
import base64
import uuid


def check_desk(req, cli, account, client, owner, password, bridge, mailboxes, root, url):
    identifier = uuid.uuid4().hex[:12]
    writer = f'write-{identifier}@example.invalid'
    member = {'email': writer, 'role': 'writer', 'enabled': True, 'version': 0}
    req('/api/staff/team', 'POST', member, owner)
    req('/api/staff/team', 'POST', member, owner, status=409)
    cli('dealer:user', writer, 'writer', inp=password+'\n')
    limited = client()
    account(limited, writer, password)
    req('/api/staff/profile', 'POST', {'username':'User_'+identifier}, limited)
    signed = client()
    account(signed, 'uSeR_'+identifier, password)
    req('/api/staff/blogs', c=signed)
    req('/api/staff/team', c=signed, status=403)
    req('/api/staff/team','POST',{**member,'version':1,'enabled':False},owner)
    req('/api/staff/session', c=signed, status=401)
    cli('dealer:user',writer,'writer',inp=password+'\n')
    blocked=next(r for r in req('/api/staff/team',c=owner)['members'] if r['email']==writer)
    assert not blocked['enabled']
    req('/api/staff/team','POST',{**member,'version':blocked['version'],'enabled':True},owner)
    req('/api/staff/session', c=signed, status=401)
    account(signed, writer, password)
    cli('dealer:revoke',writer)
    req('/api/staff/session', c=signed, status=401)
    print('PASS username login, versioned team changes, disable/restore and credential revocation',flush=True)

    # The seller photo printed in the ticket is private and remains private after a duplicate submission.
    tiny_jpeg = base64.b64decode('/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAP//////////////////////////////////////////////////////////////////////////////////////2wBDAf//////////////////////////////////////////////////////////////////////////////////////wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAf/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAf/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwCfwAB//9k=')
    sell={'requestId':str(uuid.uuid4()),'name':'Seller demo','email':f'seller-{identifier}@example.invalid','vehicle':'Example shuttle','sellerVehicle':{'mileage':15000,'seats':10,'accessible':True,'boarding':'ramp','wheelchairPositions':1,'photos':[base64.b64encode(tiny_jpeg).decode()]}}
    receipt=req('/api/sell','POST',sell,status=201)
    assert req('/api/sell','POST',sell)==receipt
    tid=receipt['ticketId']
    state=req('/api/staff/data',c=owner)
    entry=next(t for t in state['tickets'] if t['id']==tid)
    assert entry['seller_photo_count']==1 and entry['seller_wheelchair_positions']==1 and 'Boarding equipment: Ramp' in entry['question']
    photo_path=f'/api/staff/tickets/{tid}/seller-photos/1'
    req(photo_path,status=401)
    req(photo_path,c=owner)
    req('/api/inquiries','POST',{},status=403,headers={'Origin':'https://another.example.invalid'})
    req('/api/inquiries','POST',{'padding':'z'*32769},status=413)
    req('/api/staff/tickets/'+tid,'PATCH',{'stage':'conversation','version':entry['version'],'kind':'call_reached','note':'Confirmed accessible entry.'},owner)
    req('/api/staff/tickets/'+tid,'PATCH',{'stage':'new','version':entry['version']},owner,status=409)
    print('PASS private seller photo, ramp and mileage, duplicate submission, ticket note, stale update and buyer form limits',flush=True)

    # Drive the same consume-and-acknowledge protocol used by the dealership-owned Apps Script.
    addresses={f'arrival-en-{identifier}@example.invalid':'en', f'arrival-es-{identifier}@example.invalid':'es'}
    for email,lang in addresses.items(): req('/api/subscribers','POST',{'email':email,'language':lang})
    key=req('/api/staff/sender','POST',{'action':'key'},owner)['key']
    def arrive(action,**params):
        return req('/api/arrivals/bridge','POST',{'mailbox':mailboxes[1],'action':action,**params},headers={'Authorization':'Bearer '+key})
    arrive('tested')
    cover=req('/api/staff/photos','POST',tiny_jpeg,owner,headers={'Content-Type':'image/jpeg'})['path']
    stock='QA'+identifier.upper()
    data={'stock':stock,'title':'Sample shuttle','miles':'30000','seats':'12 passengers plus driver','passengerSeats':12,'wheelchairPositions':0,'luggage':'','lift':'','description':'Sample listing.','price':22000,'images':[cover],'action':'publish_notify','version':0,'nonCdl':True,'video':''}
    published=req('/api/staff/inventory','POST',data,owner)
    assert published['queued']>=2
    assert arrive('next')['item'] is None
    req('/api/staff/sender','POST',{'action':'enable'},owner)
    deliveries={}
    for _ in range(published['queued']+1):
        item=arrive('next')['item']
        if item is None:break
        assert item['email'] not in deliveries and item['stock']==stock
        deliveries[item['email']]=item
        arrive('result',claim=item['claim'],state='sent')
    assert arrive('next')['item'] is None and set(addresses)<=set(deliveries)
    for email,lang in addresses.items():
        item=deliveries[email]
        assert item['language']==lang and item['image']==cover and item['unsubscribe']
    spanish=next(e for e,l in addresses.items() if l=='es')
    req('/api/unsubscribe','POST',{'token':deliveries[spanish]['unsubscribe']})
    req('/api/unsubscribe','POST',{'token':deliveries[spanish]['unsubscribe']})
    merge=bridge(2,'export',{'scope':'subscribers','cursor':''})['rows']
    opted=next(r for r in merge if r['email']==spanish)
    assert opted['status']=='unsubscribed' and opted['language']=='es' and 'token' not in opted
    print('PASS opt-in, English/Spanish new-arrival claims, pause/enable, one delivery per recipient, opt-out reflected in Sheets',flush=True)
