import {activeCustomerSession} from '@/lib/customer-auth';
import {authBody,authFailure,AuthError} from '@/lib/customer-auth';
import {db,json} from '@/lib/server';
import {validName,latinDigits} from '@/lib/auth-input';
import {bankRegistrationInput,bankErrors,bankError} from '@/lib/bank-registration';
import {nationalIdValid,type IdentityState} from '@/lib/identity';
import type {DashboardData} from '@/lib/dashboard';
import {validGregorianBirthDate} from '@/lib/birth-date';
async function tokenFor(request:Request){const state=await activeCustomerSession(request);return state.token;}

async function rpc<T={ok?:boolean;id?:string;code?:string}>(name:string,body:unknown,token:string,timeout=10000):Promise<T>{
 const response=await db('rpc/'+name,{method:'POST',body:JSON.stringify(body),signal:AbortSignal.timeout(timeout)},token);
 const data=await response.json() as {ok?:boolean;id?:string;message?:string;code?:string};
 if(!response.ok){
  const message=typeof data?.message==='string'?data.message:'';
  if(bankErrors[message])throw new AuthError(bankErrors[message],409);
  if(message==='birth_date_locked')throw new AuthError('تاریخ تولد با ثبت‌احوال تطبیق داده شده است. برای اصلاح آن با پشتیبانی تماس بگیرید.',409);
  if(message.includes('verified_profile_locked'))throw new AuthError('تغییر مشخصات تأییدشده نیازمند بررسی پشتیبانی است.');
  if(data?.code==='23505')throw new AuthError('این اطلاعات قبلاً ثبت شده است.');
  if(message.includes('bank_limit'))throw new AuthError('حداکثر ۱۰ حساب بانکی می‌توانید ثبت کنید.');
  if(message.includes('alert_limit'))throw new AuthError('حداکثر ۲۰ هشدار می‌توانید ثبت کنید.');
  if(name==='marketplace_bank_register'&&(response.status===404||data?.code==='PGRST202'))return {ok:false,code:'bank_registration_unavailable'} as T;
  if(response.status===404||data?.code==='PGRST202')throw new AuthError('داشبورد در حال آماده‌سازی است. کمی بعد دوباره تلاش کنید.',503);
  throw new AuthError('ذخیره یا دریافت اطلاعات انجام نشد. دوباره تلاش کنید.',response.status>=500?503:400);
 }
 return data as T;
}
// Older databases keep the full national ID in the identity request, not the account.
// Read it through the existing self-only RPC; never derive it from masked digits.
async function profileState(token:string){
 const dashboard=await rpc<DashboardData>('marketplace_dashboard',{},token);
 if(!dashboard.account||nationalIdValid(dashboard.account.national_id||''))return dashboard;
 const identity=await rpc<IdentityState>('marketplace_identity_state',{},token);
 const request=identity.request;
 const nationalId=request&&['draft','pending','documents_approved','verified'].includes(request.status)&&nationalIdValid(request.national_id||'')?request.national_id:null;
 return {...dashboard,account:{...dashboard.account,national_id:nationalId,national_id_editable:!nationalId&&'national_id' in dashboard.account}};
}
export async function GET(request:Request){try{const token=await tokenFor(request);return json(await profileState(token))}catch(e){return authFailure(e)}}
export async function POST(request:Request){try{
 const body=await authBody(request),token=await tokenFor(request),action=body.action;
 const payload=body.payload;if(!payload||typeof payload!=='object'||Array.isArray(payload))throw new AuthError('اطلاعات معتبر نیست.');
 const p=payload as Record<string,unknown>;let safe:Record<string,unknown>={};
 if(action==='profile'){
  if(!validName(p.first_name)||!validName(p.last_name))throw new AuthError('نام و نام خانوادگی را وارد کنید.');
  if(p.birth_date&&(typeof p.birth_date!=='string'||!validGregorianBirthDate(p.birth_date)))throw new AuthError('تاریخ تولد معتبر نیست یا در آینده قرار دارد.');
  safe={first_name:p.first_name.trim(),last_name:p.last_name.trim(),birth_date:p.birth_date||null};
  if('national_id' in p){const nid=latinDigits(String(p.national_id||'')).trim();if(!nationalIdValid(nid))throw new AuthError('کد ملی ده‌رقمی معتبر وارد کنید.');safe.national_id=nid;}
  if(safe.national_id){
   const current=await profileState(token);
   if(current.account.national_id_editable===false){
    if(current.account.national_id!==safe.national_id)throw new AuthError('کد ملی از بخش احراز هویت ثبت می‌شود. مشخصات هویتی را از دکمه بالای داشبورد تکمیل یا پیگیری کنید.',409);
    // The submitted ID is already persisted with the uploaded identity documents.
    // Do not send an unsupported field to a function that silently ignores it.
    delete safe.national_id;
   }
  }
 }else if(action==='preferences'){
  for(const key of ['hide_balances','hide_small_assets','email_notifications','confirm_orders','confirm_cancellations','reduced_motion'])if(key in p){if(typeof p[key]!=='boolean')throw new AuthError('تنظیمات معتبر نیست.');safe[key]=p[key]}
  if('theme' in p){if(!['dark','light'].includes(String(p.theme)))throw new AuthError('تم معتبر نیست.');safe.theme=p.theme}
  if('locale' in p){if(!['fa','en','ar'].includes(String(p.locale)))throw new AuthError('زبان معتبر نیست.');safe.locale=p.locale}
  if('currency' in p){if(!['TMN','USDT'].includes(String(p.currency)))throw new AuthError('واحد معتبر نیست.');safe.currency=p.currency}
 }else if(action==='bank_add'){
  let bankInput;try{bankInput=bankRegistrationInput(p)}catch(e){throw new AuthError((e as Error).message)}
  const result=await rpc('marketplace_bank_register',bankInput,token,25000);
  if(result.ok!==true)return json({ok:false,code:result.code||'provider_unavailable',error:bankError(result.code||'')},result.code==='bank_registration_unavailable'?503:result.code==='bank_not_matched'?422:409);
  return json({ok:true,id:result.id});
 }else if(action==='alert_add'){
  if(!uuid(p.project_id)||!['above','below'].includes(String(p.direction))||typeof p.target_price_rial!=='string'||!/^\d{1,30}$/.test(p.target_price_rial)||BigInt(p.target_price_rial)<=BigInt(0))throw new AuthError('پروژه و قیمت معتبر انتخاب کنید.');
  safe={project_id:p.project_id,direction:p.direction,target_price_rial:p.target_price_rial};
 }else if(['bank_remove','bank_primary','alert_remove','api_revoke'].includes(String(action))){if(!uuid(p.id))throw new AuthError('شناسه معتبر نیست.');safe={id:p.id}}
 else if(action==='notification_read'){if(p.id!==undefined&&!uuid(p.id))throw new AuthError('شناسه معتبر نیست.');safe=p.id?{id:p.id}:{}}
 else throw new AuthError('درخواست پشتیبانی نمی‌شود.');
 await rpc('marketplace_dashboard_update',{action,payload:safe},token);
 if(action==='profile'&&safe.national_id){
  const saved=await profileState(token);
  if(saved.account.national_id!==safe.national_id)throw new AuthError('کد ملی ذخیره نشد. اطلاعات را تازه‌سازی کنید و از بخش احراز هویت پیگیری کنید.',409);
 }
 return json({ok:true});
}catch(e){return authFailure(e)}}
function uuid(value:unknown){return typeof value==='string'&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)}
