"""Local integration checks; run against the development server only."""
import json, urllib.request, urllib.error, uuid
BASE='http://localhost:3000'
uid='relto-test-'+str(uuid.uuid4())
def call(path='',body=None,identity=True):
    headers={'Origin':BASE,'Content-Type':'application/json'}
    if identity: headers.update({'Cookie':'__sites_local_auth=1'})
    req=urllib.request.Request(BASE+'/api/market'+path,headers=headers,data=json.dumps(body).encode() if body is not None else None)
    try:
        with urllib.request.urlopen(req) as r: return r.status,json.load(r)
    except urllib.error.HTTPError as e:return e.code,json.load(e)
assert call('?view=account',identity=False)[0]==401
assert call(body={'action':'request'},identity=False)[0]==401
account_code,account=call('?view=account');assert account_code==200,(account_code,account)
original=account['profile']
assert call(body={'action':'profile','name':'Integration test','phone':'+40700000000','notifyApp':True})[0]==200
payload={'action':'request','title':'Cerere temporară de test','type':'Apartamente','deal':'Cumpărare','city':'Test local','county':'Test','budget':100000,'area':60,'rooms':2,'description':'Înregistrare de integrare temporară, nu este o cerere reală.'}
code,created=call(body=payload);assert code==200,(code,created)
rid=created['id']
try:
    code,public=call('?view=request&id='+rid,identity=False);assert code==200
    assert not any(k in public for k in ['phone','contact_phone','owner']),public
    assert call(body={'action':'favorite','id':rid})[0]==200
    assert call(body={'action':'offer','id':rid})[0]==400
    assert call('?view=messages&id=unknown')[0]==403
    assert call(body={'action':'message','id':rid,'body':'unauthorized'})[0]==403
    assert call(body={**payload,'urgent':True})[0]==400
    assert call(body={'action':'status','id':rid,'status':'inactive'})[0]==200
    assert call('?view=request&id='+rid,identity=False)[0]==404
    assert call(body={'action':'favorite','id':rid,'remove':True})[0]==200
    assert call(body={'action':'status','id':rid,'status':'active'})[0]==200
    print('PASS: authentication, private contact, request publication, ownership, favorite removal, insufficient balance, chat authorization and lifecycle')
finally:
    call(body={'action':'status','id':rid,'status':'deleted'})
    call(body={'action':'profile','name':original['name'],'phone':original['phone'],'notifyApp':original['notify_app'],'notifyEmail':original['notify_email']})
