<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Spatie\Permission\Models\Permission;

/**
 * Item 3.1 / 3.2 / 2.2 — Block low-rated pet owners.
 *
 *  clc_patient_contact_details      gains block state: is_blocked, blocked_at,
 *                            blocked_reason, blocked_by, credit_limit_backup
 *                            (so an admin can restore the prior limit
 *                            when unblocking, per the 3.2 prompt).
 *
 *  clc_block_settings         per-business policy: enable_auto_block,
 *                            block_rating_threshold (percentage, default
 *                            25%), min_ratings_to_evaluate (skip owners
 *                            with too few ratings to be meaningful),
 *                            block_zero_credit_limit (when blocking,
 *                            also zero the contact's credit limit -
 *                            recommended ON for high-risk).
 *
 *  Permissions: clinic.manage_owner_blocking (admin/high-level
 *  manager only - the "checklist for administration" role mentioned
 *  in the task) and clinic.view_owner_blocking (read-only).
 */
class ClcCreateBlockingPolicy extends Migration
{
    public function up()
    {
        if (!Schema::hasColumn('clc_patient_contact_details', 'is_blocked')) {
            Schema::table('clc_patient_contact_details', function (Blueprint $table) {
                $table->boolean('is_blocked')->default(false)->index();
                $table->timestamp('blocked_at')->nullable();
                $table->text('blocked_reason')->nullable();
                $table->unsignedInteger('blocked_by')->nullable();
                // Snapshot of the contact's credit limit at block-time so
                // unblocking can offer "restore or keep at zero".
                $table->decimal('credit_limit_backup', 14, 2)->nullable();
                // Snapshot of the cumulative rating that caused the block,
                // so admins reviewing the checklist see why it triggered.
                $table->decimal('block_avg_rating', 3, 2)->nullable();
                $table->unsignedSmallInteger('block_rating_count')->nullable();
            });
        }

        if (!Schema::hasTable('clc_block_settings')) {
            Schema::create('clc_block_settings', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('business_id')->unique();
                $table->boolean('enable_auto_block')->default(false);
                // Threshold expressed as percentage of the rating max
                // (5-star scale: 25% = 1.25 stars). Default per the spec.
                $table->unsignedTinyInteger('block_rating_threshold')->default(25);
                // Skip the check until the owner has at least this many
                // ratings - avoids blocking new clients on a single bad
                // review.
                $table->unsignedTinyInteger('min_ratings_to_evaluate')->default(3);
                // On block, also zero the contact's credit limit.
                $table->boolean('block_zero_credit_limit')->default(true);
                $table->timestamps();
            });
        }

        foreach ([
            'clinic.manage_owner_blocking',
            'clinic.view_owner_blocking',
        ] as $p) {
            Permission::findOrCreate($p, 'web');
        }
    }

    public function down()
    {
        if (Schema::hasColumn('clc_patient_contact_details', 'is_blocked')) {
            Schema::table('clc_patient_contact_details', function (Blueprint $table) {
                $table->dropColumn([
                    'is_blocked','blocked_at','blocked_reason','blocked_by',
                    'credit_limit_backup','block_avg_rating','block_rating_count',
                ]);
            });
        }
        Schema::dropIfExists('clc_block_settings');
        foreach ([
            'clinic.manage_owner_blocking',
            'clinic.view_owner_blocking',
        ] as $p) {
            Permission::where('name', $p)->delete();
        }
    }
}
