/* Bernard Health SeniorCare V4.3.21 — compatibilidad y diagnóstico de funciones Supabase */
(function(){
  'use strict';
  if(window.__BHSC_DATABASE_COMPAT_V4321)return;
  window.__BHSC_DATABASE_COMPAT_V4321=true;

  const VERSION='4.3.25';
  const db=()=>window.seniorcareSupabase||null;
  const text=e=>String(e?.message||e||'').trim();
  const missing=e=>/could not find the function|function .* does not exist|schema cache|pgrst202|42883/i.test(text(e));
  const permission=e=>/permission denied|not allowed|not authorized|row-level security|42501/i.test(text(e));

  async function callRpc(names,args={}){
    const client=db();
    if(!client) return {data:null,error:{message:'No se pudo conectar con Supabase.'},functionName:null};
    const list=(Array.isArray(names)?names:[names]).filter(Boolean);
    let last={data:null,error:{message:'No se indicó una función RPC.'},functionName:null};
    for(const name of list){
      try{
        const result=await client.rpc(name,args);
        last={...(result||{}),functionName:name};
        if(!result?.error)return last;
        if(!missing(result.error))return last;
      }catch(error){
        last={data:null,error,functionName:name};
        if(!missing(error))return last;
      }
    }
    return last;
  }

  function friendly(error,fallback='No se pudo completar la operación.'){
    const message=text(error);
    if(missing(error))return 'Falta instalar la actualización SQL V4.3.25 en Supabase.';
    if(permission(error))return 'La cuenta no tiene permiso para realizar esta acción.';
    return window.BHSC_FRIENDLY_ERROR?.(error,fallback)||message||fallback;
  }

  async function directPlatformAccessFallback(){
    const client=db(); const u=window.currentUser;
    if(!client||!u?.id)return {allowed:true,reason:'no_session'};
    const role=String(u.role||'').toLowerCase();
    if(role==='supervisor')return {allowed:true,role};
    const profileResult=await client.from('profiles')
      .select('id,organization_id,role,active')
      .eq('id',u.id)
      .maybeSingle();
    if(profileResult.error)throw profileResult.error;
    const profile=profileResult.data;
    if(!profile)return {allowed:false,reason:'profile_missing'};
    if(profile.active===false)return {allowed:false,reason:'profile_inactive'};
    const orgId=profile.organization_id||u.organizationId||u.organization_id;
    if(!orgId)return {allowed:false,reason:'organization_missing'};

    const [orgResult,licenseResult,moduleResult]=await Promise.all([
      client.from('organizations').select('id,active').eq('id',orgId).maybeSingle(),
      client.from('licenses').select('status,renews_at,payment_confirmed').eq('organization_id',orgId).maybeSingle(),
      client.from('organization_module_subscriptions').select('module_key,enabled').eq('organization_id',orgId).eq('module_key',role).maybeSingle()
    ]);
    if(orgResult.error)throw orgResult.error;
    if(licenseResult.error)throw licenseResult.error;
    if(moduleResult.error&&!/relation .* does not exist|could not find the table/i.test(text(moduleResult.error)))throw moduleResult.error;
    if(orgResult.data&&orgResult.data.active===false)return {allowed:false,reason:'organization_inactive'};
    const lic=licenseResult.data;
    if(lic){
      const status=String(lic.status||'').toLowerCase();
      if(['suspended','cancelled'].includes(status))return {allowed:false,reason:'license_inactive'};
      if(lic.payment_confirmed&&lic.renews_at&&new Date(lic.renews_at).getTime()<Date.now())return {allowed:false,reason:'license_expired'};
    }
    if(moduleResult.data&&moduleResult.data.enabled===false)return {allowed:false,reason:'module_disabled'};
    return {allowed:true,role,organization_id:orgId,compatibility_fallback:true};
  }


  async function verifyDatabase({silent=false}={}){
    const result=await callRpc(['bh_database_status_v4325','bh_database_status_v4321'],{});
    if(result.error){
      window.BHSC_DATABASE_READY=false;
      if(!silent)window.showToast?.(friendly(result.error,'Falta preparar la base de datos.'));
      return {ready:false,error:result.error};
    }
    const row=Array.isArray(result.data)?result.data[0]:result.data;
    const ready=row?.ready===true&&String(row?.version||'')===VERSION;
    window.BHSC_DATABASE_READY=ready;
    window.BHSC_DATABASE_STATUS=row||{};
    if(!ready&&!silent)window.showToast?.('La base de datos no corresponde a la versión 4.3.25.');
    return {ready,data:row||{}};
  }

  window.BHSC_CALL_RPC=callRpc;
  window.BHSC_RPC_FUNCTION_MISSING=missing;
  window.BHSC_DATABASE_FRIENDLY_ERROR=friendly;
  window.BHSC_DIRECT_PLATFORM_ACCESS_FALLBACK=directPlatformAccessFallback;
  window.BHSC_VERIFY_DATABASE=verifyDatabase;
  window.BHSC_DATABASE_COMPAT_VERSION=VERSION;
  window.addEventListener('seniorcare:user-ready',()=>verifyDatabase({silent:false}),{once:true});
  console.info(`Compatibilidad Supabase ${VERSION} lista`);
})();
