<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

class Inspection extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'inspection_collection_id',
        'property_name',
        'property_address',
        'status',
        'ai_confidence',
        'estimated_cost',
        'currency_code',
        'estimated_cost_label',
        'scheduled_at',
        'completed_at',
        'source_image_paths',
        'visualization_image_paths',
        'roboflow_output_keys',
        'roboflow_outputs',
        'analysis_settings',
        'groq_analysis_outputs',
    ];

    protected function casts(): array
    {
        return [
            'ai_confidence' => 'decimal:2',
            'estimated_cost' => 'decimal:2',
            'scheduled_at' => 'datetime',
            'completed_at' => 'datetime',
            'source_image_paths' => 'array',
            'visualization_image_paths' => 'array',
            'roboflow_output_keys' => 'array',
            'roboflow_outputs' => 'array',
            'analysis_settings' => 'array',
            'groq_analysis_outputs' => 'array',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (Inspection $inspection) {
            if ($inspection->inspection_collection_id || ! $inspection->user_id) {
                return;
            }

            $workspace = InspectionWorkspace::query()->firstOrCreate(
                ['user_id' => $inspection->user_id, 'name' => 'Default Workspace'],
                ['default_currency' => $inspection->currency_code ?: 'IDR', 'metadata' => ['created_from' => 'model']]
            );

            $propertyName = trim((string) ($inspection->property_name ?: 'General Collection'));
            $collection = InspectionCollection::query()->firstOrCreate(
                [
                    'user_id' => $inspection->user_id,
                    'inspection_workspace_id' => $workspace->id,
                    'property_name' => $propertyName,
                    'room_name' => null,
                ],
                [
                    'name' => $propertyName,
                    'collection_type' => 'house',
                    'property_address' => $inspection->property_address,
                    'metadata' => ['created_from' => 'inspection_model'],
                ]
            );

            $inspection->inspection_collection_id = $collection->id;
        });

        static::saving(function (Inspection $inspection) {
            $currency = in_array($inspection->currency_code, ['IDR', 'USD'], true) ? $inspection->currency_code : 'IDR';
            $inspection->currency_code = $currency;

            if (! $inspection->estimated_cost_label && $inspection->estimated_cost !== null) {
                $inspection->estimated_cost_label = $currency === 'USD'
                    ? '$'.number_format((float) $inspection->estimated_cost, 2, '.', ',')
                    : 'Rp '.number_format((float) $inspection->estimated_cost, 0, ',', '.');
            }
        });
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function collection(): BelongsTo
    {
        return $this->belongsTo(InspectionCollection::class, 'inspection_collection_id');
    }

    public function damageFindings(): HasMany
    {
        return $this->hasMany(DamageFinding::class);
    }

    public function report(): HasOne
    {
        return $this->hasOne(InspectionReport::class);
    }
}
