-- =============================================================================
-- AURGANIZE V6.2 - INITIAL SCHEMA ROLLBACK
-- =============================================================================
-- Migration: 000001_initial_schema (DOWN)
-- Description: Safely removes all tables, functions, triggers, and types
-- Author: Aurganize Team
-- Date: 2025-12-11
-- Version: 2.0 (Marketplace Edition)
-- =============================================================================
-- This rollback migration removes the entire Aurganize V6.2 schema in the
-- correct order to avoid foreign key constraint violations.
--
-- CRITICAL SAFETY NOTES:
-- 1. This will DESTROY ALL DATA in the database
-- 2. Always backup before running this migration
-- 3. Cannot be undone - data recovery requires restoring from backup
-- 4. Runs in reverse dependency order (child tables before parent tables)
--
-- Order of operations:
-- 1. Drop all RLS policies
-- 2. Drop all triggers
-- 3. Drop all tables (child → parent order)
-- 4. Drop all functions
-- 5. Drop all custom types
-- 6. Drop all extensions (optional - usually kept for other schemas)
-- =============================================================================

-- =============================================================================
-- SECTION 1: DISABLE ROW-LEVEL SECURITY
-- =============================================================================
-- Must disable RLS before dropping policies
-- =============================================================================

-- Disable RLS on all tables (if they exist)
ALTER TABLE IF EXISTS notifications DISABLE ROW LEVEL SECURITY;
ALTER TABLE IF EXISTS analytics_events DISABLE ROW LEVEL SECURITY;
ALTER TABLE IF EXISTS audit_logs DISABLE ROW LEVEL SECURITY;
ALTER TABLE IF EXISTS attachments DISABLE ROW LEVEL SECURITY;
ALTER TABLE IF EXISTS comments DISABLE ROW LEVEL SECURITY;
ALTER TABLE IF EXISTS milestones DISABLE ROW LEVEL SECURITY;
ALTER TABLE IF EXISTS deliverables DISABLE ROW LEVEL SECURITY;
ALTER TABLE IF EXISTS contracts DISABLE ROW LEVEL SECURITY;
ALTER TABLE IF EXISTS users DISABLE ROW LEVEL SECURITY;
ALTER TABLE IF EXISTS tenants DISABLE ROW LEVEL SECURITY;

-- =============================================================================
-- SECTION 2: DROP ROW-LEVEL SECURITY POLICIES
-- =============================================================================
-- Drop policies before dropping tables
-- Using IF EXISTS to prevent errors if policies don't exist
-- =============================================================================

-- Notifications policies
DROP POLICY IF EXISTS notifications_tenant_isolation ON notifications;

-- Analytics policies
DROP POLICY IF EXISTS analytics_events_access ON analytics_events;

-- Audit logs policies
DROP POLICY IF EXISTS audit_logs_tenant_isolation ON audit_logs;

-- Attachments policies
DROP POLICY IF EXISTS attachments_collaboration_access ON attachments;

-- Comments policies
DROP POLICY IF EXISTS comments_collaboration_access ON comments;

-- Milestones policies
DROP POLICY IF EXISTS milestones_collaboration_access ON milestones;

-- Deliverables policies
DROP POLICY IF EXISTS deliverables_collaboration_access ON deliverables;

-- Contracts policies
DROP POLICY IF EXISTS contracts_collaboration_access ON contracts;

-- Users policies
DROP POLICY IF EXISTS users_marketplace_access ON users;

-- Tenants policies
DROP POLICY IF EXISTS tenants_marketplace_access ON tenants;

-- =============================================================================
-- SECTION 3: DROP ALL TRIGGERS
-- =============================================================================
-- Triggers must be dropped before functions they reference
-- Drop in any order (triggers are independent)
-- =============================================================================

-- Updated_at triggers (applied to multiple tables)
DROP TRIGGER IF EXISTS update_tenants_updated_at ON tenants;
DROP TRIGGER IF EXISTS update_users_updated_at ON users;
DROP TRIGGER IF EXISTS update_contracts_updated_at ON contracts;
DROP TRIGGER IF EXISTS update_deliverables_updated_at ON deliverables;
DROP TRIGGER IF EXISTS update_milestones_updated_at ON milestones;
DROP TRIGGER IF EXISTS update_comments_updated_at ON comments;
DROP TRIGGER IF EXISTS update_attachments_updated_at ON attachments;

-- Full name generation trigger (users table)
DROP TRIGGER IF EXISTS update_user_full_name ON users;

-- =============================================================================
-- SECTION 4: DROP ALL TABLES
-- =============================================================================
-- CRITICAL ORDER: Drop child tables BEFORE parent tables
-- Foreign key constraints prevent dropping parent tables first
--
-- Dependency tree:
-- notifications → tenants, users
-- analytics_events → tenants, users
-- audit_logs → tenants, users
-- attachments → tenants, users
-- comments → tenants, users
-- milestones → tenants, deliverables
-- deliverables → tenants, contracts
-- contracts → tenants, users
-- users → tenants
-- tenants (root)
-- =============================================================================

-- Level 4: Supporting tables (no dependencies)
DROP TABLE IF EXISTS notifications CASCADE;
DROP TABLE IF EXISTS analytics_events CASCADE;
DROP TABLE IF EXISTS audit_logs CASCADE;

-- Level 3: Polymorphic relationship tables (depend on multiple entities)
DROP TABLE IF EXISTS attachments CASCADE;
DROP TABLE IF EXISTS comments CASCADE;

-- Level 2: Milestones → Deliverables
DROP TABLE IF EXISTS milestones CASCADE;

-- Level 1: Deliverables → Contracts
DROP TABLE IF EXISTS deliverables CASCADE;

-- Level 0: Core business tables
DROP TABLE IF EXISTS contracts CASCADE;
DROP TABLE IF EXISTS users CASCADE;
DROP TABLE IF EXISTS tenants CASCADE;

-- =============================================================================
-- SECTION 5: DROP ALL FUNCTIONS
-- =============================================================================
-- Functions can be dropped after triggers that use them
-- Order doesn't matter for functions
-- =============================================================================

-- Trigger function for updating updated_at timestamps
DROP FUNCTION IF EXISTS update_updated_at_column() CASCADE;

-- Trigger function for generating full_name from first_name + last_name
DROP FUNCTION IF EXISTS generate_full_name() CASCADE;

-- =============================================================================
-- SECTION 6: DROP ALL CUSTOM TYPES
-- =============================================================================
-- Types must be dropped after all tables/functions that use them
-- Order doesn't matter for types (no dependencies between types)
-- =============================================================================

-- Drop all ENUM types
DROP TYPE IF EXISTS milestone_status CASCADE;
DROP TYPE IF EXISTS milestone_type CASCADE;
DROP TYPE IF EXISTS deliverable_status CASCADE;
DROP TYPE IF EXISTS contract_status CASCADE;
DROP TYPE IF EXISTS user_role CASCADE;

-- =============================================================================
-- SECTION 7: DROP EXTENSIONS (OPTIONAL)
-- =============================================================================
-- WARNING: Only drop extensions if you're certain no other schemas use them
-- Usually extensions are shared across the entire database
-- Commented out by default for safety
-- =============================================================================

-- Uncomment only if you're certain these extensions are not used elsewhere:
-- DROP EXTENSION IF EXISTS "unaccent" CASCADE;
-- DROP EXTENSION IF EXISTS "btree_gin" CASCADE;
-- DROP EXTENSION IF EXISTS "pg_trgm" CASCADE;
-- DROP EXTENSION IF EXISTS "uuid-ossp" CASCADE;

-- =============================================================================
-- SECTION 8: VERIFICATION QUERIES (OPTIONAL)
-- =============================================================================
-- Run these after rollback to verify complete removal
-- These queries should return 0 rows if rollback was successful
-- =============================================================================

-- Verify no tables remain from our schema
DO $$
DECLARE
    remaining_tables INTEGER;
BEGIN
    SELECT COUNT(*) INTO remaining_tables
    FROM information_schema.tables
    WHERE table_schema = 'public'
    AND table_name IN (
        'tenants', 'users', 'contracts', 'deliverables', 'milestones',
        'comments', 'attachments', 'audit_logs', 'analytics_events', 'notifications'
    );
    
    IF remaining_tables > 0 THEN
        RAISE WARNING 'WARNING: % tables still exist after rollback', remaining_tables;
    ELSE
        RAISE NOTICE 'SUCCESS: All Aurganize tables removed';
    END IF;
END $$;

-- Verify no custom types remain
DO $$
DECLARE
    remaining_types INTEGER;
BEGIN
    SELECT COUNT(*) INTO remaining_types
    FROM pg_type
    WHERE typname IN (
        'user_role', 'contract_status', 'deliverable_status', 
        'milestone_type', 'milestone_status'
    );
    
    IF remaining_types > 0 THEN
        RAISE WARNING 'WARNING: % custom types still exist after rollback', remaining_types;
    ELSE
        RAISE NOTICE 'SUCCESS: All Aurganize custom types removed';
    END IF;
END $$;

-- Verify no functions remain
DO $$
DECLARE
    remaining_functions INTEGER;
BEGIN
    SELECT COUNT(*) INTO remaining_functions
    FROM pg_proc
    WHERE proname IN ('update_updated_at_column', 'generate_full_name');
    
    IF remaining_functions > 0 THEN
        RAISE WARNING 'WARNING: % functions still exist after rollback', remaining_functions;
    ELSE
        RAISE NOTICE 'SUCCESS: All Aurganize functions removed';
    END IF;
END $$;

-- =============================================================================
-- END OF ROLLBACK MIGRATION 000001_initial_schema.down.sql
-- =============================================================================
