<?php

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

// ══════════════════════════════════════════════════════════════════
//  InPractice — Freelance Matchmaking Tables
//
//  Connects professionals who offer services with businesses
//  or individuals who need them.
//
//  The platform ONLY makes the introduction.
//  No payments. No contracts. No escrow. Just the connection.
//
//  Flow:
//    1. Professional creates freelance_profile (what they offer)
//    2. Business creates freelance_brief (what they need)
//    3. Platform surfaces matching profiles
//    4. Seeker sends interest → freelance_match created (pending)
//    5. Freelancer reviews the brief and responds
//    6. Both consent → contact details shared → platform done
//    7. After engagement → both leave reviews
//
//  Tables:
//    freelance_profiles → service providers
//    freelance_briefs   → service requests
//    freelance_matches  → the connection between the two
//    reviews            → post-engagement ratings
// ══════════════════════════════════════════════════════════════════

return new class extends Migration
{
    public function up(): void
    {
        // ── Freelance Profiles ─────────────────────────────────
        Schema::create('freelance_profiles', function (Blueprint $table) {
            $table->id();

            $table->foreignId('user_id')
                  ->constrained('users')
                  ->cascadeOnDelete();

            $table->foreignId('hub_id')
                  ->constrained('hubs')
                  ->cascadeOnDelete();

            // ── What They Offer ───────────────────────────────
            $table->string('headline');                      // e.g. "Financial Modelling & Feasibility Studies"
            $table->text('description');                     // detailed description of services
            $table->json('services');                        // array of specific services offered
            $table->json('sector_expertise')->nullable();    // sectors they know well
            $table->string('experience_level');              // junior | mid | senior

            // ── Availability ──────────────────────────────────
            $table->enum('availability', [
                'weekends',          // weekends only
                'evenings',          // evenings after work
                'full',              // fully available
                'unavailable',       // temporarily not taking work
            ])->default('weekends');

            // ── Rate ──────────────────────────────────────────
            $table->unsignedInteger('rate_min_egp')->nullable();  // minimum day rate in EGP
            $table->unsignedInteger('rate_max_egp')->nullable();  // maximum day rate in EGP
            $table->boolean('rate_is_visible')->default(true);    // show rate or keep private

            // ── Ratings Summary (cached) ───────────────────────
            $table->unsignedInteger('review_count')->default(0);
            $table->decimal('rating_average', 3, 2)->default(0.00);

            // ── Status ────────────────────────────────────────
            $table->boolean('is_active')->default(true);

            // Contact is NEVER shown here — stored in users table
            // Only shared after mutual consent in freelance_matches

            $table->timestamps();
        });

        // ── Freelance Briefs ───────────────────────────────────
        Schema::create('freelance_briefs', function (Blueprint $table) {
            $table->id();

            $table->foreignId('user_id')
                  ->constrained('users')
                  ->cascadeOnDelete();

            $table->foreignId('hub_id')
                  ->constrained('hubs')
                  ->cascadeOnDelete();

            // ── What They Need ────────────────────────────────
            $table->string('title');                         // short description of need
            $table->text('description');                     // full details of what they need
            $table->json('required_skills')->nullable();     // skills they're looking for
            $table->string('preferred_sector')->nullable();  // industry context preferred

            // ── Engagement Details ────────────────────────────
            $table->string('duration_estimate')->nullable(); // e.g. "2-3 days", "1 week"
            $table->string('timeline')->nullable();          // when they need it done
            $table->unsignedInteger('budget_min_egp')->nullable();
            $table->unsignedInteger('budget_max_egp')->nullable();
            $table->boolean('budget_is_visible')->default(true);

            // ── Status ────────────────────────────────────────
            $table->enum('status', [
                'open',              // accepting applications
                'in_progress',       // matched with someone
                'closed',            // completed or cancelled
            ])->default('open');

            $table->timestamps();
        });

        // ── Freelance Matches ──────────────────────────────────
        Schema::create('freelance_matches', function (Blueprint $table) {
            $table->id();

            $table->foreignId('freelance_brief_id')
                  ->constrained('freelance_briefs')
                  ->cascadeOnDelete();

            $table->foreignId('freelance_profile_id')
                  ->constrained('freelance_profiles')
                  ->cascadeOnDelete();

            // The seeker who posted the brief
            $table->foreignId('seeker_user_id')
                  ->constrained('users')
                  ->cascadeOnDelete();

            // The freelancer being contacted
            $table->foreignId('provider_user_id')
                  ->constrained('users')
                  ->cascadeOnDelete();

            // ── Status Flow ───────────────────────────────────
            // pending    → seeker sent interest, freelancer hasn't responded
            // interested → freelancer wants to connect
            // declined   → freelancer not interested
            // connected  → both consented, contact shared
            $table->enum('status', [
                'pending',
                'interested',
                'declined',
                'connected',
            ])->default('pending');

            // ── Consent Tracking ──────────────────────────────
            $table->boolean('seeker_consented')->default(false);
            $table->boolean('provider_consented')->default(false);
            $table->timestamp('connected_at')->nullable();

            // ── Message ───────────────────────────────────────
            $table->text('seeker_message')->nullable();      // initial message from seeker

            $table->timestamps();
        });

        // ── Reviews ────────────────────────────────────────────
        Schema::create('reviews', function (Blueprint $table) {
            $table->id();

            $table->foreignId('freelance_match_id')
                  ->constrained('freelance_matches')
                  ->cascadeOnDelete();

            // Who wrote the review
            $table->foreignId('reviewer_user_id')
                  ->constrained('users')
                  ->cascadeOnDelete();

            // Who the review is about (the freelancer's profile)
            $table->foreignId('freelance_profile_id')
                  ->constrained('freelance_profiles')
                  ->cascadeOnDelete();

            // ── Review Content ────────────────────────────────
            $table->unsignedTinyInteger('rating');           // 1-5 stars
            $table->text('comment')->nullable();
            $table->boolean('posted_as_nickname')->default(true);

            $table->timestamps();

            // One review per match per reviewer
            $table->unique(['freelance_match_id', 'reviewer_user_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('reviews');
        Schema::dropIfExists('freelance_matches');
        Schema::dropIfExists('freelance_briefs');
        Schema::dropIfExists('freelance_profiles');
    }
};
