-- ============================================================================
-- PUBLIC GRANTS FOR ROA APPLICATION
-- ============================================================================
-- Grants necessary permissions on CONTAFIN_ORACLE objects to PUBLIC
-- and configures network ACLs for CONTAFIN_ORACLE
--
-- Usage:
--   @grants-public.sql
--
-- Connect as: SYSTEM or SYS as SYSDBA
-- Must run AFTER:
--   1. CONTAFIN_ORACLE schema objects are imported
--   2. synonyms-public.sql has been executed
-- ============================================================================

SET ECHO OFF
SET FEEDBACK ON
SET SERVEROUTPUT ON
WHENEVER SQLERROR CONTINUE

PROMPT
PROMPT ========================================
PROMPT Granting Permissions to PUBLIC
PROMPT ========================================
PROMPT

-- ============================================================================
-- SECTION 1: GRANTS ON CORE USER/PROGRAM TABLES
-- ============================================================================

PROMPT [1/9] Granting SELECT/REFERENCES on core tables...

-- DEF_GRUP
GRANT SELECT ON SYN_DEF_GRUP TO PUBLIC;
GRANT REFERENCES ON SYN_DEF_GRUP TO PUBLIC;

-- DEF_PROGRAME
GRANT SELECT ON SYN_DEF_PROGRAME TO PUBLIC;
GRANT REFERENCES ON SYN_DEF_PROGRAME TO PUBLIC;

-- VDEF_PROGRAME
GRANT SELECT ON SYN_VDEF_PROGRAME TO PUBLIC;
GRANT REFERENCES ON SYN_VDEF_PROGRAME TO PUBLIC;

-- LUNILEAN
GRANT SELECT ON SYN_LUNILEAN TO PUBLIC;
GRANT REFERENCES ON SYN_LUNILEAN TO PUBLIC;

-- NOM_FIRME
GRANT SELECT ON SYN_NOM_FIRME TO PUBLIC;
GRANT REFERENCES ON SYN_NOM_FIRME TO PUBLIC;

-- NOM_PROGRAME
GRANT SELECT ON SYN_NOM_PROGRAME TO PUBLIC;
GRANT REFERENCES ON SYN_NOM_PROGRAME TO PUBLIC;

-- UTILIZATORI
GRANT SELECT ON SYN_UTILIZATORI TO PUBLIC;
GRANT REFERENCES ON SYN_UTILIZATORI TO PUBLIC;

-- VDEF_UTIL_PROGRAME
GRANT SELECT ON SYN_VDEF_UTIL_PROGRAME TO PUBLIC;

-- VDEF_UTIL_FIRME
GRANT SELECT ON SYN_VDEF_UTIL_FIRME TO PUBLIC;
GRANT REFERENCES ON SYN_VDEF_UTIL_FIRME TO PUBLIC;

-- VDEF_UTIL_OBIECTE
GRANT SELECT ON SYN_VDEF_UTIL_OBIECTE TO PUBLIC;
GRANT REFERENCES ON SYN_VDEF_UTIL_OBIECTE TO PUBLIC;

-- VUTILIZATORI
GRANT SELECT ON SYN_VUTILIZATORI TO PUBLIC;
GRANT REFERENCES ON SYN_VUTILIZATORI TO PUBLIC;

-- VDEF_UTIL_GRUP
GRANT SELECT ON SYN_VDEF_UTIL_GRUP TO PUBLIC;
GRANT REFERENCES ON SYN_VDEF_UTIL_GRUP TO PUBLIC;

-- DEF_GRUP_DREPT
GRANT SELECT ON SYN_DEF_GRUP_DREPT TO PUBLIC;
GRANT REFERENCES ON SYN_DEF_GRUP_DREPT TO PUBLIC;

-- OPTIUNI_PROGRAME
GRANT SELECT ON SYN_OPTIUNI_PROGRAME TO PUBLIC;

-- HELPCONT
GRANT SELECT ON SYN_HELPCONT TO PUBLIC;

-- V_NOM_FIRME
GRANT SELECT ON SYN_V_NOM_FIRME TO PUBLIC;

-- ============================================================================
-- SECTION 2: GRANTS ON UTILITY TYPES AND FUNCTIONS
-- ============================================================================

PROMPT [2/9] Granting EXECUTE on utility types/functions...

GRANT EXECUTE ON STRINGAGG TO PUBLIC;
GRANT EXECUTE ON CONTAFIN_ORACLE.STRINGAGGTYPE TO PUBLIC;

GRANT EXECUTE ON CHAR_ROW TO PUBLIC;
GRANT EXECUTE ON CHAR_TAB TO PUBLIC;
GRANT EXECUTE ON NUM_ROW TO PUBLIC;
GRANT EXECUTE ON NUM_TAB TO PUBLIC;

GRANT EXECUTE ON UW_SEL_ROW TO PUBLIC;
GRANT EXECUTE ON UW_SEL_TAB TO PUBLIC;

GRANT EXECUTE ON VALOARETAG TO PUBLIC;
GRANT EXECUTE ON GETWORDCOUNT TO PUBLIC;
GRANT EXECUTE ON GETWORDNUM TO PUBLIC;
GRANT EXECUTE ON CHARC2COLLECTION TO PUBLIC;
GRANT EXECUTE ON CHARN2COLLECTION TO PUBLIC;

-- ============================================================================
-- SECTION 3: GRANTS ON NOMENCLATURE TABLES
-- ============================================================================

PROMPT [3/9] Granting SELECT/REFERENCES on nomenclature tables...

-- Legal forms
GRANT SELECT ON SYN_NOM_FORME_JURIDICE TO PUBLIC;
GRANT REFERENCES ON SYN_NOM_FORME_JURIDICE TO PUBLIC;

GRANT SELECT ON SYN_NOM_FORME_ORGANIZARE TO PUBLIC;
GRANT REFERENCES ON SYN_NOM_FORME_ORGANIZARE TO PUBLIC;

GRANT SELECT ON SYN_NOM_TIP_SOCIETATE TO PUBLIC;
GRANT REFERENCES ON SYN_NOM_TIP_SOCIETATE TO PUBLIC;

GRANT SELECT ON SYN_NOM_FORME_PROPRIETATE TO PUBLIC;
GRANT REFERENCES ON SYN_NOM_FORME_PROPRIETATE TO PUBLIC;

-- Geography
GRANT SELECT ON SYN_NOM_CETATENII TO PUBLIC;
GRANT REFERENCES ON SYN_NOM_CETATENII TO PUBLIC;

GRANT SELECT ON SYN_NOM_TARI TO PUBLIC;
GRANT REFERENCES ON SYN_NOM_TARI TO PUBLIC;

GRANT SELECT ON SYN_NOM_JUDETE TO PUBLIC;
GRANT REFERENCES ON SYN_NOM_JUDETE TO PUBLIC;

GRANT SELECT ON SYN_NOM_LOCALITATI TO PUBLIC;
GRANT REFERENCES ON SYN_NOM_LOCALITATI TO PUBLIC;

GRANT SELECT ON SYN_VNOM_JUDETE TO PUBLIC;
GRANT SELECT ON SYN_VNOM_LOCALITATI TO PUBLIC;
GRANT SELECT ON SYN_VNOM_TARI TO PUBLIC;

GRANT SELECT ON SYN_NOM_CODURI_CAEN TO PUBLIC;
GRANT REFERENCES ON SYN_NOM_CODURI_CAEN TO PUBLIC;

GRANT SELECT ON SYN_NOM_TIPAPATRID TO PUBLIC;
GRANT REFERENCES ON SYN_NOM_TIPAPATRID TO PUBLIC;

-- ============================================================================
-- SECTION 4: GRANTS ON CURRENCY/EXCHANGE TABLES
-- ============================================================================

PROMPT [4/9] Granting SELECT/REFERENCES on currency tables...

GRANT SELECT ON SYN_VNOM_VALUTE_ISO TO PUBLIC;

GRANT SELECT ON SYN_NOM_VALUTE_ISO TO PUBLIC;
GRANT REFERENCES ON SYN_NOM_VALUTE_ISO TO PUBLIC;

GRANT SELECT ON SYN_CURS_COTATII TO PUBLIC;
GRANT REFERENCES ON SYN_CURS_COTATII TO PUBLIC;

GRANT SELECT ON SYN_CURS_ACTUALIZARI TO PUBLIC;
GRANT REFERENCES ON SYN_CURS_ACTUALIZARI TO PUBLIC;

GRANT SELECT, REFERENCES ON SYN_VNOM_UM_ISO TO PUBLIC;
GRANT SELECT, REFERENCES ON CONTAFIN_ORACLE.NOM_UM_ISO TO PUBLIC;

-- ============================================================================
-- SECTION 5: GRANTS ON SALARY MODULE TABLES AND TYPES
-- ============================================================================

PROMPT [5/9] Granting permissions on salary module objects...

-- Nomenclature tables
GRANT SELECT ON SYN_SAL_NOM_TEMEI TO PUBLIC;
GRANT REFERENCES ON SYN_SAL_NOM_TEMEI TO PUBLIC;

GRANT SELECT ON SYN_SAL_NOM_TIPAUTORIZATIE TO PUBLIC;
GRANT REFERENCES ON SYN_SAL_NOM_TIPAUTORIZATIE TO PUBLIC;

GRANT SELECT ON SYN_SAL_NOM_TIP_SPOR TO PUBLIC;
GRANT REFERENCES ON SYN_SAL_NOM_TIP_SPOR TO PUBLIC;

GRANT SELECT ON SYN_SAL_NOM_TIP_NORME TO PUBLIC;
GRANT REFERENCES ON SYN_SAL_NOM_TIP_NORME TO PUBLIC;

GRANT SELECT ON SYN_SAL_NOM_STARI_CTR TO PUBLIC;
GRANT REFERENCES ON SYN_SAL_NOM_STARI_CTR TO PUBLIC;

GRANT SELECT ON SYN_SAL_NOM_DURATA_MUNCA TO PUBLIC;
GRANT REFERENCES ON SYN_SAL_NOM_DURATA_MUNCA TO PUBLIC;

GRANT SELECT ON SYN_SAL_NOM_REPARTIZARE_MUNCA TO PUBLIC;
GRANT REFERENCES ON SYN_SAL_NOM_REPARTIZARE_MUNCA TO PUBLIC;

GRANT SELECT ON SYN_SAL_NOM_INTERVALE_MUNCA TO PUBLIC;
GRANT REFERENCES ON SYN_SAL_NOM_INTERVALE_MUNCA TO PUBLIC;

GRANT SELECT ON SYN_SAL_COR TO PUBLIC;
GRANT REFERENCES ON SYN_SAL_COR TO PUBLIC;

GRANT SELECT ON SYN_SAL_ACTUALIZARE_COR TO PUBLIC;
GRANT REFERENCES ON SYN_SAL_ACTUALIZARE_COR TO PUBLIC;

-- Salary types
GRANT EXECUTE ON CONTAFIN_ORACLE.SAL_CONTRACT_M TO PUBLIC;
GRANT EXECUTE ON CONTAFIN_ORACLE.CONTRACT_M TO PUBLIC;
GRANT EXECUTE ON SAL_CONTRACT_M TO PUBLIC;
GRANT EXECUTE ON CONTRACT_M TO PUBLIC;
GRANT EXECUTE ON SAL_RED TO PUBLIC;
GRANT EXECUTE ON SAL_CAMPURI_RED TO PUBLIC;
GRANT EXECUTE ON TABSTERS TO PUBLIC;
GRANT EXECUTE ON SAL_TABELESTERS TO PUBLIC;

-- ============================================================================
-- SECTION 6: GRANTS ON ATTACHMENT TABLES
-- ============================================================================

PROMPT [6/9] Granting permissions on attachment tables...

GRANT SELECT ON SYN_ATAS_ATASAMENTE TO PUBLIC;
GRANT REFERENCES ON SYN_ATAS_ATASAMENTE TO PUBLIC;

GRANT SELECT ON SYN_ATAS_REFERINTE TO PUBLIC;
GRANT REFERENCES ON SYN_ATAS_REFERINTE TO PUBLIC;

-- ============================================================================
-- SECTION 7: GRANTS ON PACKAGES AND ADDITIONAL TYPES
-- ============================================================================

PROMPT [7/9] Granting EXECUTE on packages and types...

-- Packages
GRANT EXECUTE ON SYN_PACK_DREPTURI TO PUBLIC;
GRANT EXECUTE ON PACK_UPDATE TO PUBLIC;
GRANT EXECUTE ON PACK_UTILS TO PUBLIC;
GRANT EXECUTE ON PACK_UTILS_FILE TO PUBLIC;
GRANT EXECUTE ON SYN_PACK_DEF_CO TO PUBLIC;
GRANT EXECUTE ON PACK_ROARTVAI TO PUBLIC;

-- Additional types
GRANT EXECUTE ON FF_SUME TO PUBLIC;
GRANT EXECUTE ON FF_PERSINTRET TO PUBLIC;
GRANT EXECUTE ON VANZARI_DETALII_TAB TO PUBLIC;
GRANT EXECUTE ON PIVOT_TABLE TO PUBLIC;
GRANT EXECUTE ON PIVOT_ROW TO PUBLIC;
GRANT EXECUTE ON TABINCHIDERETVA TO PUBLIC;
GRANT EXECUTE ON TABELAVALORITAGURI TO PUBLIC;
GRANT EXECUTE ON RANDINCHIDERETVA TO PUBLIC;

-- SERVER_INFO table
GRANT SELECT, UPDATE ON SERVER_INFO TO PUBLIC;

-- RTVAI module
GRANT SELECT ON RTVAI_AGENTI TO PUBLIC;
GRANT SELECT ON RTVAI_ISTORIC TO PUBLIC;

-- License view synonym
GRANT SELECT ON CONTAFIN_ORACLE.VDEF_PROGRAME_SERII TO CONTAFIN_ORACLE;

-- ============================================================================
-- SECTION 8: DIRECTORY AND SYSTEM GRANTS
-- ============================================================================

PROMPT [8/9] Granting directory and system permissions...

-- DMPDIR directory should already exist (created by 01-setup-database.ps1)
-- Only grant permissions here - don't override the path
-- If DMPDIR doesn't exist, create with standard path C:\DMPDIR
DECLARE
    v_count NUMBER;
BEGIN
    SELECT COUNT(*) INTO v_count FROM dba_directories WHERE directory_name = 'DMPDIR';
    IF v_count = 0 THEN
        EXECUTE IMMEDIATE 'CREATE DIRECTORY DMPDIR AS ''C:\DMPDIR''';
        DBMS_OUTPUT.PUT_LINE('  Created DMPDIR directory (C:\DMPDIR)');
    ELSE
        DBMS_OUTPUT.PUT_LINE('  DMPDIR directory already exists - preserving existing path');
    END IF;
EXCEPTION
    WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE('Note: DMPDIR ' || SQLERRM);
END;
/

-- Grant directory access
GRANT ALL ON DIRECTORY DMPDIR TO PUBLIC;

-- Grant UTL packages to PUBLIC
GRANT EXECUTE ON UTL_FILE TO PUBLIC;
GRANT EXECUTE ON DBMS_LOCK TO PUBLIC;

-- Grant UTL packages to CONTAFIN_ORACLE specifically
GRANT EXECUTE ON UTL_INADDR TO CONTAFIN_ORACLE;
GRANT EXECUTE ON UTL_TCP TO CONTAFIN_ORACLE;
GRANT EXECUTE ON UTL_SMTP TO CONTAFIN_ORACLE;
GRANT EXECUTE ON UTL_HTTP TO CONTAFIN_ORACLE;

-- UTL_MAIL may not exist in all Oracle editions
BEGIN
    EXECUTE IMMEDIATE 'GRANT EXECUTE ON UTL_MAIL TO CONTAFIN_ORACLE';
EXCEPTION
    WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE('Note: UTL_MAIL not available (requires configuration)');
END;
/

-- ============================================================================
-- SECTION 9: NETWORK ACL CONFIGURATION
-- ============================================================================

PROMPT [9/9] Configuring Network ACL for CONTAFIN_ORACLE...

-- Drop existing ACL (if exists)
BEGIN
    DBMS_NETWORK_ACL_ADMIN.DROP_ACL(acl => 'roaupdate.xml');
    DBMS_OUTPUT.PUT_LINE('Dropped existing roaupdate.xml ACL');
EXCEPTION
    WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE('Note: roaupdate.xml ACL did not exist (this is OK)');
END;
/

-- Create new ACL with permissions for CONTAFIN_ORACLE
BEGIN
    DBMS_NETWORK_ACL_ADMIN.CREATE_ACL(
        acl         => 'roaupdate.xml',
        description => 'Permissions for ROA application network access',
        principal   => 'CONTAFIN_ORACLE',
        is_grant    => TRUE,
        privilege   => 'connect'
    );

    DBMS_NETWORK_ACL_ADMIN.ADD_PRIVILEGE(
        acl       => 'roaupdate.xml',
        principal => 'CONTAFIN_ORACLE',
        is_grant  => TRUE,
        privilege => 'resolve'
    );

    -- Allow all hosts (use specific hosts in production)
    DBMS_NETWORK_ACL_ADMIN.ASSIGN_ACL(
        acl  => 'roaupdate.xml',
        host => '*'
    );

    DBMS_OUTPUT.PUT_LINE('Network ACL created successfully for CONTAFIN_ORACLE');
END;
/

COMMIT;

-- ============================================================================
-- VERIFICATION
-- ============================================================================

PROMPT
PROMPT ========================================
PROMPT Grants Complete - Verification
PROMPT ========================================
PROMPT

PROMPT Grants to PUBLIC on CONTAFIN_ORACLE objects:
SELECT grantee, table_name, privilege
FROM dba_tab_privs
WHERE grantee = 'PUBLIC'
  AND grantor = 'SYS'
  AND table_name LIKE 'SYN_%'
ORDER BY table_name, privilege;

PROMPT
PROMPT Network ACL assignments for CONTAFIN_ORACLE:
SELECT host, lower_port, upper_port, acl
FROM dba_network_acls
WHERE acl LIKE '%roaupdate%';

PROMPT
PROMPT ACL privileges:
SELECT acl, principal, privilege, is_grant
FROM dba_network_acl_privileges
WHERE acl LIKE '%roaupdate%';

PROMPT
PROMPT Directory permissions:
SELECT grantee, table_name, privilege
FROM dba_tab_privs
WHERE table_name = 'DMPDIR';

-- ============================================================================
-- SECTION 10: GRANTS ON UNDERLYING TABLES FOR SYS OBJECTS
-- ============================================================================
-- SYS.AUTH_PACK needs direct access to CONTAFIN_ORACLE tables through synonyms
-- These grants ensure SYS-owned objects can resolve synonym references

PROMPT [10/11] Granting table access for SYS objects...

-- Tables accessed by SYS.AUTH_PACK
GRANT SELECT ON CONTAFIN_ORACLE.NOM_PROGRAME TO PUBLIC;
GRANT SELECT ON CONTAFIN_ORACLE.DEF_PROGRAME TO PUBLIC;
GRANT SELECT ON CONTAFIN_ORACLE.AUTH_SERII TO PUBLIC;
GRANT SELECT ON CONTAFIN_ORACLE.AUTH_DETALII TO PUBLIC;

-- Tables accessed by VAUTH_SERII view
GRANT SELECT ON CONTAFIN_ORACLE.VDEF_PROGRAME TO PUBLIC;

-- ============================================================================
-- SECTION 11: RECOMPILE SYS AND CONTAFIN_ORACLE OBJECTS
-- ============================================================================

PROMPT [11/11] Recompiling SYS and CONTAFIN_ORACLE objects...

-- Recompile SYS.AUTH_PACK (depends on synonyms now available)
ALTER PACKAGE SYS.AUTH_PACK COMPILE;
ALTER PACKAGE SYS.AUTH_PACK COMPILE BODY;

-- Grant EXECUTE on SYS.AUTH_PACK so CONTAFIN_ORACLE.PACK_DREPTURI can call it
-- through the PACK_AUTENTIFICARE synonym
GRANT EXECUTE ON SYS.AUTH_PACK TO PUBLIC;

-- Recreate VAUTH_SERII view (may have been invalid due to missing synonym)
-- This view uses SYN_NOM_PROGRAME for program names and AUTH_PACK functions for license info
BEGIN
    EXECUTE IMMEDIATE '
    CREATE OR REPLACE VIEW SYS.VAUTH_SERII AS
    SELECT a.id_program,
           a.denumire AS nume,
           auth_pack.selecteaza_serie(a.id_program) AS serie,
           auth_pack.selecteaza_nr_util(a.id_program) AS nr_util,
           auth_pack.selecteaza_data_val(a.id_program) AS data_val
      FROM syn_nom_programe a
      LEFT JOIN syn_def_programe b ON a.id_program = b.ide_program
     WHERE b.sters = 0
       AND b.instalat = 1';
    DBMS_OUTPUT.PUT_LINE('  View VAUTH_SERII created/replaced.');
EXCEPTION
    WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE('  Warning: Could not create VAUTH_SERII: ' || SQLERRM);
END;
/

GRANT SELECT ON SYS.VAUTH_SERII TO PUBLIC;

-- Recompile CONTAFIN_ORACLE invalid objects
PROMPT Recompiling CONTAFIN_ORACLE schema...
BEGIN
    DBMS_UTILITY.COMPILE_SCHEMA(schema => 'CONTAFIN_ORACLE', compile_all => FALSE);
END;
/

-- Show remaining invalid objects
PROMPT
PROMPT Remaining invalid objects (excluding email procedures):
SELECT owner, object_name, object_type
FROM dba_objects
WHERE owner IN ('SYS', 'CONTAFIN_ORACLE')
  AND status = 'INVALID'
  AND object_type NOT IN ('SYNONYM')
  AND object_name NOT IN ('SENDEMAIL', 'EMAILINCASARI', 'EMAILNOTIFICAREFACTURI', 'EMAILSTOCCRITIC')
ORDER BY owner, object_type, object_name;

PROMPT
PROMPT ========================================
PROMPT Grant Configuration Complete
PROMPT ========================================
PROMPT
