<?php

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

/**
 * Dental's structural extension of the shared ClinicCore patient. Unlike a
 * flat field set (Dermatology), dental data is a per-tooth chart, so it needs
 * two tables: a 1:1 profile and a 1:many tooth-findings table — both keyed to
 * clc_patients. This is the plugin half of the ClinicCore specialty
 * architecture; the DentalSpecialtyDriver reads/writes these and renders the
 * tooth chart into ClinicCore's shared patient screens.
 */
class CreateDentalSpecialtyTables extends Migration
{
    public function up()
    {
        if (! Schema::hasTable('clc_patients')) return; // requires ClinicCore

        if (! Schema::hasTable('dental_patient_profiles')) {
            Schema::create('dental_patient_profiles', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('clc_patient_id');
                $table->enum('dentition_type', ['adult', 'child', 'mixed'])->default('adult');
                $table->text('notes')->nullable();
                $table->timestamps();

                $table->unique('clc_patient_id');
                $table->foreign('clc_patient_id')->references('id')->on('clc_patients')->onDelete('cascade');
            });
        }

        if (! Schema::hasTable('dental_tooth_findings')) {
            Schema::create('dental_tooth_findings', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedInteger('clc_patient_id');
                $table->unsignedTinyInteger('tooth_number'); // Universal numbering 1..32
                $table->string('condition', 30)->default('healthy');
                $table->string('surfaces', 20)->nullable();  // M,O,D,B,L combinations
                $table->text('note')->nullable();
                $table->timestamps();

                $table->unique(['clc_patient_id', 'tooth_number']);
                $table->foreign('clc_patient_id')->references('id')->on('clc_patients')->onDelete('cascade');
            });
        }
    }

    public function down()
    {
        Schema::dropIfExists('dental_tooth_findings');
        Schema::dropIfExists('dental_patient_profiles');
    }
}
