-- =============================================================================
-- Export DDL + date din MARIUSM_AUTO pentru audit service-auto
-- =============================================================================
-- Utilizare:
--   1. Deschide SQL Developer (sau sqlplus) conectat ca MARIUSM_AUTO
--      (sau orice user cu SELECT_CATALOG_ROLE)
--   2. Rulează tot scriptul (F5 în SQL Developer)
--   3. Output-ul apare în panoul "Script Output" — selectează tot, copiază,
--      trimite la Claude (sau salvează în fișier)
--
-- Output-ul conține:
--   - DDL pentru tabele DEV_*, NOM_LUCRARI, RUL, ACT, VANZARI
--   - DDL pentru pachete PACK_AUTO, PACK_FACTURARE, PACK_SESIUNE, PACK_CONTAFIN
--   - DDL pentru triggere TRG_DEV_*, TRG_NOM_LUCRARI_*
--   - DDL pentru views AUTO_*, DEV_V*, DEV_COMENZI_VALIDATE
--   - Conținutul enum DEV_TIP_DEVIZ (live)
--   - Coloanele live din DEV_ORDL, DEV_MASINICLIENTI, DEV_ESTIMARI_REP
--
-- Alternativ pentru sqlplus cu spool în fișier:
--   sqlplus MARIUSM_AUTO/parola@10.0.20.121:1521/ROA @export_ddl.sql
--   → fișierul `mariusm_ddl_export.log` e generat în directorul curent
-- =============================================================================

SET SERVEROUTPUT ON SIZE UNLIMITED
SET LINESIZE 32767
SET LONG 100000000
SET LONGCHUNKSIZE 32767
SET PAGESIZE 0
SET FEEDBACK OFF
SET VERIFY OFF
SET HEADING OFF
SET TRIMSPOOL ON
SET TRIMOUT ON
SET WRAP OFF

-- Spool DOAR dacă rulezi din sqlplus. SQL Developer ignoră această linie dacă
-- nu folosește `@script`. În SQL Developer pur, rezultatul apare în "Script Output".
SPOOL mariusm_ddl_export.log

-- Schema țintă — modifică dacă testezi pe alt user
DEFINE schema_name = 'MARIUSM_AUTO'

-- =============================================================================
-- Config DBMS_METADATA pentru DDL curat (fără storage/segment noise)
-- =============================================================================
BEGIN
  DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM, 'STORAGE', FALSE);
  DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM, 'SEGMENT_ATTRIBUTES', FALSE);
  DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM, 'TABLESPACE', FALSE);
  DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM, 'PRETTY', TRUE);
  DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM, 'SQLTERMINATOR', TRUE);
END;
/

PROMPT
PROMPT =============================================================================
PROMPT == MARIUSM_AUTO DDL EXPORT — start
PROMPT == Data rulare: &_DATE
PROMPT =============================================================================
PROMPT

-- =============================================================================
-- BLOCUL MARE: tot exportul rulează într-un PL/SQL anonim care folosește
-- DBMS_OUTPUT.PUT_LINE ca să scrie totul în ordinea dorită.
-- Marca de secțiune e `-- === SECTION: <nume> ===` ca să o putem parsa ulterior.
-- =============================================================================
DECLARE
  v_schema       VARCHAR2(30) := '&schema_name';
  v_ddl          CLOB;
  v_offset       NUMBER;
  v_chunk_size   NUMBER := 30000;
  v_length       NUMBER;

  -- Liste de obiecte de exportat — pattern-urile sunt SQL LIKE cu ESCAPE '\'
  TYPE t_patterns IS TABLE OF VARCHAR2(100);

  -- Tabele relevante
  v_table_patterns t_patterns := t_patterns(
    'DEV\_%',             -- toate DEV_* (ordl, oper, nom_norme, tip_deviz, estimari_rep, masiniclienti, ...)
    'NOM\_LUCRARI',
    'NOM\_ARTICOLE',
    'RUL',
    'ACT',
    'VANZARI',
    'CONTRACTE',
    'CTR\_ARTICOLE',
    'CALENDAR',
    'NOM\_PARTENERI',
    'PARTENERI'
  );

  -- Views relevante
  v_view_patterns t_patterns := t_patterns(
    'AUTO\_%',            -- AUTO_NORMARE_COMENZI, AUTO_ORDL_FACTURARE, AUTO_VNORME
    'DEV\_V%',            -- DEV_VORDL, DEV_VOPER, DEV_VVALID_COMENZI
    'DEV\_COMENZI\_VALIDATE',
    'VCOMENZI',
    'VNOM\_%'
  );

  -- Triggere relevante
  v_trigger_patterns t_patterns := t_patterns(
    'TRG\_DEV\_%',
    'TRG\_NOM\_LUCRARI\_%'
  );

  -- Pachete — listă explicită (DBMS_METADATA cere nume exact pentru PACKAGE)
  TYPE t_packages IS TABLE OF VARCHAR2(30);
  v_packages t_packages := t_packages(
    'PACK_AUTO',
    'PACK_FACTURARE',
    'PACK_SESIUNE',
    'PACK_CONTAFIN',
    'PACK_COMENZI',
    'PACK_TYPES'
  );

  -- =====================================================
  -- Helper: print CLOB în chunk-uri (DBMS_OUTPUT limit = 32767/linie)
  -- =====================================================
  PROCEDURE print_clob(p_clob IN CLOB) IS
    v_pos  NUMBER := 1;
    v_line VARCHAR2(32767);
    v_nl   NUMBER;
  BEGIN
    IF p_clob IS NULL THEN RETURN; END IF;
    WHILE v_pos <= DBMS_LOB.GETLENGTH(p_clob) LOOP
      v_nl := DBMS_LOB.INSTR(p_clob, CHR(10), v_pos);
      IF v_nl = 0 OR v_nl - v_pos > 32000 THEN
        v_line := DBMS_LOB.SUBSTR(p_clob, LEAST(32000, DBMS_LOB.GETLENGTH(p_clob) - v_pos + 1), v_pos);
        DBMS_OUTPUT.PUT_LINE(v_line);
        v_pos := v_pos + LENGTH(v_line);
      ELSE
        v_line := DBMS_LOB.SUBSTR(p_clob, v_nl - v_pos, v_pos);
        DBMS_OUTPUT.PUT_LINE(v_line);
        v_pos := v_nl + 1;
      END IF;
    END LOOP;
  END;

  -- =====================================================
  -- Helper: export un grup de obiecte descoperite prin LIKE pe ALL_OBJECTS
  -- =====================================================
  PROCEDURE export_group(
    p_object_type IN VARCHAR2,
    p_patterns    IN t_patterns,
    p_section     IN VARCHAR2
  ) IS
    v_where_clause VARCHAR2(4000);
    v_sql          VARCHAR2(4000);
    TYPE t_names IS TABLE OF VARCHAR2(128);
    v_names t_names;
  BEGIN
    DBMS_OUTPUT.PUT_LINE('');
    DBMS_OUTPUT.PUT_LINE('-- ============================================================');
    DBMS_OUTPUT.PUT_LINE('-- === SECTION: ' || p_section || ' ===');
    DBMS_OUTPUT.PUT_LINE('-- ============================================================');

    -- Build WHERE clause din pattern-uri
    v_where_clause := '';
    FOR i IN 1 .. p_patterns.COUNT LOOP
      IF i > 1 THEN v_where_clause := v_where_clause || ' OR '; END IF;
      v_where_clause := v_where_clause ||
        'object_name LIKE ''' || p_patterns(i) || ''' ESCAPE ''\''';
    END LOOP;

    v_sql := 'SELECT object_name FROM all_objects ' ||
             'WHERE owner = :1 AND object_type = :2 AND (' || v_where_clause || ') ' ||
             'ORDER BY object_name';

    EXECUTE IMMEDIATE v_sql BULK COLLECT INTO v_names USING v_schema, p_object_type;

    DBMS_OUTPUT.PUT_LINE('-- Găsite: ' || v_names.COUNT || ' obiecte');
    DBMS_OUTPUT.PUT_LINE('');

    FOR i IN 1 .. v_names.COUNT LOOP
      BEGIN
        DBMS_OUTPUT.PUT_LINE('-- --- ' || p_object_type || ': ' || v_names(i) || ' ---');
        v_ddl := DBMS_METADATA.GET_DDL(p_object_type, v_names(i), v_schema);
        print_clob(v_ddl);
        DBMS_OUTPUT.PUT_LINE('');
      EXCEPTION
        WHEN OTHERS THEN
          DBMS_OUTPUT.PUT_LINE('-- ERROR la ' || v_names(i) || ': ' || SQLERRM);
      END;
    END LOOP;
  END;

  -- =====================================================
  -- Helper: export pachet (spec + body separate)
  -- =====================================================
  PROCEDURE export_package(p_name IN VARCHAR2) IS
    v_exists NUMBER;
  BEGIN
    SELECT COUNT(*) INTO v_exists
      FROM all_objects
     WHERE owner = v_schema
       AND object_name = p_name
       AND object_type IN ('PACKAGE', 'PACKAGE BODY');

    IF v_exists = 0 THEN
      DBMS_OUTPUT.PUT_LINE('-- SKIP ' || p_name || ' — nu există în ' || v_schema);
      RETURN;
    END IF;

    DBMS_OUTPUT.PUT_LINE('-- --- PACKAGE SPEC: ' || p_name || ' ---');
    BEGIN
      v_ddl := DBMS_METADATA.GET_DDL('PACKAGE_SPEC', p_name, v_schema);
      print_clob(v_ddl);
    EXCEPTION
      WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE('-- ERROR spec: ' || SQLERRM);
    END;
    DBMS_OUTPUT.PUT_LINE('');

    DBMS_OUTPUT.PUT_LINE('-- --- PACKAGE BODY: ' || p_name || ' ---');
    BEGIN
      v_ddl := DBMS_METADATA.GET_DDL('PACKAGE_BODY', p_name, v_schema);
      print_clob(v_ddl);
    EXCEPTION
      WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE('-- ERROR body: ' || SQLERRM);
    END;
    DBMS_OUTPUT.PUT_LINE('');
  END;

BEGIN
  -- =====================================================
  -- 1. TABELE
  -- =====================================================
  export_group('TABLE', v_table_patterns, 'TABLES');

  -- =====================================================
  -- 2. VIEWS
  -- =====================================================
  export_group('VIEW', v_view_patterns, 'VIEWS');

  -- =====================================================
  -- 3. TRIGGERE
  -- =====================================================
  export_group('TRIGGER', v_trigger_patterns, 'TRIGGERS');

  -- =====================================================
  -- 4. PACHETE (spec + body)
  -- =====================================================
  DBMS_OUTPUT.PUT_LINE('');
  DBMS_OUTPUT.PUT_LINE('-- ============================================================');
  DBMS_OUTPUT.PUT_LINE('-- === SECTION: PACKAGES ===');
  DBMS_OUTPUT.PUT_LINE('-- ============================================================');
  DBMS_OUTPUT.PUT_LINE('');
  FOR i IN 1 .. v_packages.COUNT LOOP
    export_package(v_packages(i));
  END LOOP;
END;
/

-- =============================================================================
-- SECTION: DATA SAMPLES & COLUMN METADATA
-- =============================================================================

PROMPT
PROMPT -- ============================================================
PROMPT -- === SECTION: DATA - DEV_TIP_DEVIZ (enum live) ===
PROMPT -- ============================================================
PROMPT

SET HEADING ON
SET PAGESIZE 1000
SET FEEDBACK ON
COLUMN id_tip FORMAT 999
COLUMN denumire FORMAT A40
COLUMN sters FORMAT 9
COLUMN inch_validare FORMAT 9

SELECT id_tip, denumire, sters, inch_validare
  FROM &schema_name..dev_tip_deviz
 ORDER BY id_tip;

PROMPT
PROMPT -- ============================================================
PROMPT -- === SECTION: COLUMNS - DEV_ORDL (live schema) ===
PROMPT -- ============================================================
PROMPT

COLUMN column_name FORMAT A30
COLUMN data_type FORMAT A15
COLUMN data_length FORMAT 99999
COLUMN nullable FORMAT A3
COLUMN data_default FORMAT A20

SELECT column_name, data_type, data_length, nullable, data_default
  FROM all_tab_columns
 WHERE owner = '&schema_name'
   AND table_name = 'DEV_ORDL'
 ORDER BY column_id;

PROMPT
PROMPT -- ============================================================
PROMPT -- === SECTION: COLUMNS - DEV_OPER (live schema) ===
PROMPT -- ============================================================
PROMPT

SELECT column_name, data_type, data_length, nullable, data_default
  FROM all_tab_columns
 WHERE owner = '&schema_name'
   AND table_name = 'DEV_OPER'
 ORDER BY column_id;

PROMPT
PROMPT -- ============================================================
PROMPT -- === SECTION: COLUMNS - DEV_ESTIMARI_REP (live schema) ===
PROMPT -- ============================================================
PROMPT

SELECT column_name, data_type, data_length, nullable, data_default
  FROM all_tab_columns
 WHERE owner = '&schema_name'
   AND table_name = 'DEV_ESTIMARI_REP'
 ORDER BY column_id;

PROMPT
PROMPT -- ============================================================
PROMPT -- === SECTION: COLUMNS - DEV_MASINICLIENTI (live schema) ===
PROMPT -- ============================================================
PROMPT

SELECT column_name, data_type, data_length, nullable
  FROM all_tab_columns
 WHERE owner = '&schema_name'
   AND table_name = 'DEV_MASINICLIENTI'
 ORDER BY column_id;

PROMPT
PROMPT -- ============================================================
PROMPT -- === SECTION: COLUMNS - NOM_LUCRARI (live schema) ===
PROMPT -- ============================================================
PROMPT

SELECT column_name, data_type, data_length, nullable
  FROM all_tab_columns
 WHERE owner = '&schema_name'
   AND table_name = 'NOM_LUCRARI'
 ORDER BY column_id;

PROMPT
PROMPT -- ============================================================
PROMPT -- === SECTION: FK CONSTRAINTS pe DEV_* și NOM_LUCRARI ===
PROMPT -- ============================================================
PROMPT

COLUMN constraint_name FORMAT A30
COLUMN table_name FORMAT A25
COLUMN column_name FORMAT A25
COLUMN r_table FORMAT A25
COLUMN r_column FORMAT A25

SELECT c.constraint_name,
       c.table_name,
       cc.column_name,
       rcc.table_name AS r_table,
       rcc.column_name AS r_column
  FROM all_constraints c
  JOIN all_cons_columns cc
    ON c.owner = cc.owner
   AND c.constraint_name = cc.constraint_name
  JOIN all_cons_columns rcc
    ON c.r_owner = rcc.owner
   AND c.r_constraint_name = rcc.constraint_name
   AND cc.position = rcc.position
 WHERE c.owner = '&schema_name'
   AND c.constraint_type = 'R'
   AND (c.table_name LIKE 'DEV\_%' ESCAPE '\' OR c.table_name = 'NOM_LUCRARI')
 ORDER BY c.table_name, c.constraint_name, cc.position;

PROMPT
PROMPT -- ============================================================
PROMPT -- === SECTION: SEQUENCES (SEQ_DEV_*, SEQ_NOM_LUCRARI) ===
PROMPT -- ============================================================
PROMPT

COLUMN sequence_name FORMAT A30
COLUMN last_number FORMAT 99999999999
COLUMN increment_by FORMAT 99999

SELECT sequence_name, last_number, increment_by, cycle_flag
  FROM all_sequences
 WHERE sequence_owner = '&schema_name'
   AND (sequence_name LIKE 'SEQ\_DEV\_%' ESCAPE '\'
        OR sequence_name LIKE 'SEQ\_NOM\_LUCRARI%' ESCAPE '\'
        OR sequence_name LIKE 'SEQ\_NRORD%' ESCAPE '\')
 ORDER BY sequence_name;

PROMPT
PROMPT =============================================================================
PROMPT == MARIUSM_AUTO DDL EXPORT — done
PROMPT =============================================================================

SPOOL OFF

SET FEEDBACK ON
SET PAGESIZE 14
SET HEADING ON
