<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
 * Main Migration Script
 * Creates all optimized tables for HireCameroon job board
 * Reduces database from 35+ tables to 12 optimized tables
 */
return new class extends Migration
{
    public function up()
    {
        // 1. USERS TABLE (Enhanced)
        Schema::create('users_optimized', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            
            $table->enum('account_type', ['job_seeker', 'company_owner', 'admin'])->default('job_seeker');
            $table->enum('role', ['user', 'admin', 'moderator'])->default('user');
            $table->string('status')->default('active');
            
            // Profile information
            $table->string('phone', 20)->nullable();
            $table->string('location')->nullable();
            $table->text('bio')->nullable();
            $table->string('avatar')->nullable();
            $table->date('date_of_birth')->nullable();
            $table->enum('gender', ['male', 'female', 'other', 'prefer_not_to_say'])->nullable();
            
            // Professional information
            $table->string('current_position')->nullable();
            $table->integer('years_experience')->nullable();
            $table->string('industry')->nullable();
            $table->string('highest_education_level')->nullable();
            $table->json('education_details')->nullable();
            
            // Flexible data
            $table->json('profile_data')->nullable();
            $table->json('email_notifications')->nullable();
            $table->json('privacy_settings')->nullable();
            $table->json('preferences')->nullable();
            
            $table->timestamps();
            $table->index(['account_type', 'status']);
            $table->index(['location', 'industry']);
        });

        // 2. ORGANIZATIONS TABLE (Companies)
        Schema::create('organizations_optimized', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug')->unique();
            $table->text('description')->nullable();
            $table->string('sector')->nullable();
            
            $table->string('contact_email')->nullable();
            $table->string('contact_phone', 20)->nullable();
            $table->text('address')->nullable();
            $table->string('website')->nullable();
            
            $table->string('logo')->nullable();
            $table->string('banner_image')->nullable();
            $table->string('registration_number')->nullable();
            $table->string('tax_id')->nullable();
            
            $table->foreignId('owner_user_id')->nullable()->constrained('users_optimized')->nullOnDelete();
            $table->enum('status', ['active', 'inactive', 'pending', 'suspended'])->default('active');
            $table->string('subscription_plan')->nullable();
            $table->timestamp('subscription_expires_at')->nullable();
            
            $table->json('branding')->nullable();
            $table->json('settings')->nullable();
            $table->json('domains')->nullable();
            $table->json('custom_features')->nullable();
            $table->json('seo_data')->nullable();
            $table->json('marketing_settings')->nullable();
            
            $table->timestamps();
            $table->index(['sector', 'status']);
            $table->index(['subscription_plan', 'status']);
        });

        // 3. JOBS TABLE (Enhanced)
        Schema::create('jobs_optimized', function (Blueprint $table) {
            $table->id();
            $table->foreignId('organization_id')->constrained('organizations_optimized')->onDelete('cascade');
            $table->string('title');
            $table->string('slug')->unique();
            $table->text('description');
            $table->text('requirements')->nullable();
            $table->text('benefits')->nullable();
            
            $table->string('location')->nullable();
            $table->enum('employment_type', ['full-time', 'part-time', 'contract', 'freelance', 'internship'])->default('full-time');
            $table->enum('experience_level', ['entry', 'mid', 'senior', 'executive'])->nullable();
            $table->enum('remote_type', ['onsite', 'remote', 'hybrid'])->default('onsite');
            
            $table->decimal('salary_min', 12, 2)->nullable();
            $table->decimal('salary_max', 12, 2)->nullable();
            $table->string('currency', 3)->default('XAF');
            $table->boolean('salary_negotiable')->default(false);
            
            $table->timestamp('application_deadline')->nullable();
            $table->timestamp('featured_until')->nullable();
            $table->string('application_url')->nullable();
            
            // Anti-scam features
            $table->boolean('verified_company')->default(false);
            $table->json('scam_flags')->nullable();
            $table->enum('verification_status', ['pending', 'verified', 'rejected'])->default('pending');
            
            $table->enum('status', ['draft', 'active', 'paused', 'closed', 'expired'])->default('draft');
            $table->json('seo_data')->nullable();
            $table->json('metadata')->nullable();
            
            $table->timestamps();
            $table->index(['status', 'created_at']);
            $table->index(['location', 'employment_type']);
            $table->index(['organization_id', 'status']);
        });

        // 4. APPLICATIONS TABLE (Enhanced)
        Schema::create('applications_optimized', function (Blueprint $table) {
            $table->id();
            $table->foreignId('job_id')->constrained('jobs_optimized')->onDelete('cascade');
            $table->foreignId('user_id')->constrained('users_optimized')->onDelete('cascade');
            
            $table->enum('status', ['pending', 'reviewed', 'shortlisted', 'interview', 'offered', 'hired', 'rejected', 'withdrawn'])->default('pending');
            $table->text('cover_letter')->nullable();
            $table->string('resume_path')->nullable();
            $table->string('portfolio_url')->nullable();
            
            $table->decimal('salary_expectation', 12, 2)->nullable();
            $table->date('available_start_date')->nullable();
            $table->json('application_data')->nullable(); // Dynamic form responses
            
            $table->timestamp('interview_scheduled_at')->nullable();
            $table->text('internal_notes')->nullable();
            $table->integer('rating')->nullable(); // 1-5 rating by recruiter
            
            $table->timestamps();
            $table->unique(['job_id', 'user_id']); // Prevent duplicate applications
            $table->index(['status', 'created_at']);
            $table->index(['job_id', 'status']);
        });

        // 5. CONTENT TABLE (Universal)
        Schema::create('content_optimized', function (Blueprint $table) {
            $table->id();
            $table->enum('type', ['news', 'blog', 'announcement', 'ad', 'faq', 'email_template', 'static_page']);
            $table->string('title');
            $table->string('slug')->unique();
            $table->text('content');
            $table->text('excerpt')->nullable();
            
            $table->string('image_path')->nullable();
            $table->string('target_url')->nullable();
            $table->string('position')->nullable(); // for ads
            
            $table->foreignId('user_id')->nullable()->constrained('users_optimized')->onDelete('set null');
            $table->foreignId('organization_id')->nullable()->constrained('organizations_optimized')->onDelete('set null');
            $table->foreignId('job_id')->nullable()->constrained('jobs_optimized')->onDelete('set null');
            
            $table->enum('status', ['draft', 'published', 'archived'])->default('draft');
            $table->json('seo_data')->nullable();
            $table->json('metadata')->nullable();
            $table->integer('display_order')->default(0);
            $table->boolean('is_featured')->default(false);
            $table->timestamp('expires_at')->nullable();
            
            $table->timestamps();
            $table->index(['type', 'status']);
            $table->index(['is_featured', 'status']);
        });

        // 6. INTERACTIONS TABLE (Social Features)
        Schema::create('interactions_optimized', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users_optimized')->onDelete('cascade');
            $table->string('target_type'); // job, company, application, user, content
            $table->unsignedBigInteger('target_id');
            
            $table->enum('interaction_type', [
                'like', 'unlike', 'comment', 'reply', 'share', 'view', 
                'report', 'review', 'rating', 'follow', 'bookmark'
            ]);
            
            $table->text('content')->nullable();
            $table->integer('rating')->nullable();
            $table->foreignId('parent_id')->nullable()->constrained('interactions_optimized')->nullOnDelete();
            
            $table->enum('status', ['active', 'hidden', 'reported', 'approved', 'rejected'])->default('active');
            $table->text('moderation_notes')->nullable();
            
            $table->json('metadata')->nullable();
            $table->json('interaction_data')->nullable();
            
            $table->timestamps();
            $table->index(['user_id', 'interaction_type']);
            $table->index(['target_type', 'target_id', 'interaction_type']);
            $table->index(['status', 'created_at']);
            $table->index('parent_id');
        });

        // 7. TRANSACTIONS TABLE (Unified Billing)
        Schema::create('transactions_optimized', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable()->constrained('users_optimized')->onDelete('set null');
            $table->foreignId('organization_id')->nullable()->constrained('organizations_optimized')->onDelete('set null');
            
            $table->enum('type', [
                'subscription_payment', 'job_payment', 'refund', 'api_usage', 
                'premium_feature', 'bulk_email', 'advertisement', 'custom'
            ]);
            
            $table->decimal('amount', 10, 2)->nullable();
            $table->string('currency', 3)->default('XAF');
            $table->enum('status', ['pending', 'completed', 'failed', 'cancelled', 'refunded'])->default('pending');
            
            $table->string('provider')->nullable();
            $table->string('provider_transaction_id')->nullable();
            $table->json('provider_data')->nullable();
            
            $table->string('subscription_plan')->nullable();
            $table->dateTime('billing_period_start')->nullable();
            $table->dateTime('billing_period_end')->nullable();
            $table->json('plan_features')->nullable();
            
            $table->string('api_key_id')->nullable();
            $table->integer('api_usage_quota')->nullable();
            $table->integer('api_usage_current')->default(0);
            $table->dateTime('api_usage_reset_date')->nullable();
            $table->json('api_usage_details')->nullable();
            
            $table->json('metadata')->nullable();
            $table->text('description')->nullable();
            $table->text('notes')->nullable();
            
            $table->timestamps();
            $table->index(['user_id', 'status']);
            $table->index(['organization_id', 'type']);
            $table->index(['status', 'created_at']);
        });

        // 8. SKILLS TABLE (Enhanced)
        Schema::create('skills_optimized', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->string('category')->nullable();
            $table->text('description')->nullable();
            $table->boolean('is_verified')->default(false);
            $table->foreignId('user_id')->nullable()->constrained('users_optimized')->onDelete('set null');
            $table->integer('popularity_score')->default(0);
            $table->json('related_skills')->nullable(); // for skill matching
            $table->timestamps();
            $table->index('category');
            $table->index(['is_verified', 'popularity_score']);
        });

        // 9. SAVED_ITEMS TABLE (User Preferences)
        Schema::create('saved_items_optimized', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users_optimized')->onDelete('cascade');
            $table->enum('item_type', ['job', 'company', 'search', 'filter', 'content']);
            $table->unsignedBigInteger('item_id')->nullable();
            $table->json('query_data')->nullable(); // for saved searches
            
            $table->string('name');
            $table->text('description')->nullable();
            $table->boolean('is_auto_refresh')->default(false);
            $table->timestamp('last_checked_at')->nullable();
            $table->enum('notification_frequency', ['never', 'daily', 'weekly', 'monthly'])->default('never');
            
            $table->timestamps();
            $table->index(['user_id', 'item_type']);
        });

        // 10. ACTIVITY_LOGS TABLE (System Wide)
        Schema::create('activity_logs_optimized', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable()->constrained('users_optimized')->onDelete('set null');
            $table->foreignId('organization_id')->nullable()->constrained('organizations_optimized')->onDelete('set null');
            
            $table->string('action');
            $table->string('resource_type')->nullable();
            $table->unsignedBigInteger('resource_id')->nullable();
            $table->text('description')->nullable();
            
            $table->json('old_values')->nullable();
            $table->json('new_values')->nullable();
            
            $table->string('ip_address')->nullable();
            $table->string('user_agent')->nullable();
            $table->string('session_id')->nullable();
            
            $table->enum('severity', ['info', 'warning', 'error', 'critical'])->default('info');
            $table->enum('category', ['auth', 'activity', 'admin', 'system', 'security'])->default('activity');
            $table->json('metadata')->nullable();
            
            $table->timestamps();
            $table->index(['user_id', 'created_at']);
            $table->index(['resource_type', 'resource_id']);
            $table->index(['severity', 'created_at']);
            $table->index('category');
        });

        // 11. SETTINGS TABLE (Configuration)
        Schema::create('settings_optimized', function (Blueprint $table) {
            $table->id();
            $table->string('key')->unique();
            $table->text('value')->nullable();
            $table->enum('type', ['string', 'integer', 'float', 'boolean', 'json', 'array'])->default('string');
            
            $table->string('category')->nullable(); // site, email, payment, security, seo
            $table->boolean('is_public')->default(false);
            $table->text('description')->nullable();
            $table->json('validation_rules')->nullable();
            
            $table->foreignId('updated_by_user_id')->nullable()->constrained('users_optimized')->onDelete('set null');
            
            $table->timestamps();
            $table->index('category');
            $table->index('is_public');
        });

        // 12. SESSIONS TABLE (Enhanced)
        Schema::create('sessions_optimized', function (Blueprint $table) {
            $table->string('id')->primary();
            $table->foreignId('user_id')->nullable()->constrained('users_optimized')->onDelete('cascade');
            $table->string('ip_address', 45)->nullable();
            $table->text('user_agent')->nullable();
            $table->text('payload');
            $table->integer('last_activity')->index();
            
            $table->string('device_type')->nullable(); // desktop, mobile, tablet
            $table->string('location')->nullable();
            $table->boolean('is_active')->default(true);
            $table->string('remember_token')->nullable();
            $table->enum('login_method', ['email', 'social', 'admin'])->default('email');
            
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('sessions_optimized');
        Schema::dropIfExists('settings_optimized');
        Schema::dropIfExists('activity_logs_optimized');
        Schema::dropIfExists('saved_items_optimized');
        Schema::dropIfExists('skills_optimized');
        Schema::dropIfExists('transactions_optimized');
        Schema::dropIfExists('interactions_optimized');
        Schema::dropIfExists('content_optimized');
        Schema::dropIfExists('applications_optimized');
        Schema::dropIfExists('jobs_optimized');
        Schema::dropIfExists('organizations_optimized');
        Schema::dropIfExists('users_optimized');
    }
};