import json, urllib.request, urllib.error, http.cookiejar, datetime, time
base='http://127.0.0.1:8080/api.php?action='
cookies=http.cookiejar.CookieJar()
client=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookies))
csrf=''
def call(action,data=None,expected=200,token=None):
    headers={'Content-Type':'application/json','X-CSRF-Token':csrf if token is None else token}
    request=urllib.request.Request(base+action,data=None if data is None else json.dumps(data).encode(),headers=headers)
    try:
        response=client.open(request); code=response.status; result=json.load(response)
    except urllib.error.HTTPError as e:
        code=e.code; result=json.load(e)
    assert code==expected,(action,code,result)
    return result
call('state',expected=401)
csrf=call('session')['csrf']
call('login',{'email':'admin@aligelle.local','password':'Gelle-Demo-2026!'})
call('customer',{'name':'Blocked','phone':'000'},expected=403,token='bad')
suffix=str(time.time_ns()); name='QA-'+suffix
call('customer',{'name':name,'phone':'+252 000 000','company':'Test'})
call('tool',{'name':name,'code':name[:40],'category':'QA','quantity':3,'maintenance':1,'rate':10})
s=call('state'); t=next(t for t in s['tools'] if t['name']==name); c=next(c for c in s['customers'] if c['name']==name)
today=s['today']; due=(datetime.date.fromisoformat(today)+datetime.timedelta(days=2)).isoformat()
rental={'tool_id':t['id'],'customer_id':c['id'],'quantity':2,'start_date':today,'due_date':due,'paid':10}
call('rental',{**rental,'quantity':3},expected=422)
call('rental',{**rental,'due_date':'2026-02-31'},expected=422)
call('rental',rental)
s=call('state'); r=next(r for r in s['rentals'] if r['tool_name']==name)
assert float(r['total'])==40
assert int(next(x for x in s['tools'] if x['id']==t['id'])['rented'])==2
call('rental',{**rental,'quantity':1},expected=422)
call('tool',{'id':t['id'],'name':name,'code':name[:40],'category':'QA','quantity':1,'maintenance':0,'rate':10},expected=422)
call('payment',{'id':r['id'],'paid':31},expected=422)
call('payment',{'id':r['id'],'paid':15})
call('return',{'id':r['id'],'paid':15})
call('return',{'id':r['id'],'paid':0},expected=422)
s=call('state'); r=next(x for x in s['rentals'] if x['id']==r['id'])
assert float(r['paid'])==40 and r['returned_date']==today
assert int(next(x for x in s['tools'] if x['id']==t['id'])['rented'])==0
call('logout',{}); call('state',expected=401)
print('PASS: authentication, CSRF, stock protection, date validation, payments, returns, persistence and logout.')
