<?php

namespace Modules\AiCore\Entities;

use Illuminate\Database\Eloquent\Model;

/**
 * One clinician interaction with an AI suggestion (the audit trail).
 *
 * Actions:
 *   generated  - the AI produced a suggestion (draft/answer) that was shown
 *   applied    - the clinician inserted the suggestion into the record
 *   accepted   - the clinician explicitly accepted/acknowledged it
 *   rejected   - the clinician explicitly rejected it
 *   dismissed  - the clinician closed it without using it
 *
 * Written best-effort (never throws); read by the usage dashboard for the
 * acceptance rate.
 */
class AiFeedback extends Model
{
    protected $table = 'ai_feedback';
    protected $guarded = ['id'];

    protected $casts = [
        'meta' => 'array',
    ];

    public function scopeForBusiness($query, int $businessId)
    {
        return $query->where('business_id', $businessId);
    }

    /** Record one feedback event. Never throws — telemetry must not break a page. */
    public static function record(int $businessId, array $data): void
    {
        try {
            static::create([
                'business_id' => $businessId,
                'user_id'     => $data['user_id'] ?? auth()->id(),
                'module'      => $data['module']  ?? null,
                'feature'     => $data['feature'] ?? null,
                'action'      => (string) ($data['action'] ?? 'generated'),
                'meta'        => $data['meta'] ?? null,
            ]);
        } catch (\Throwable $e) {
            // best-effort
        }
    }

    /**
     * Per-feature acceptance counts for a business since $since:
     * how many suggestions were generated vs applied/accepted vs rejected/dismissed.
     */
    public static function acceptanceSince(int $businessId, \DateTimeInterface $since)
    {
        try {
            return static::forBusiness($businessId)
                ->where('created_at', '>=', $since)
                ->selectRaw(
                    "feature, "
                    . "SUM(action = 'generated') as generated, "
                    . "SUM(action IN ('applied','accepted')) as accepted, "
                    . "SUM(action IN ('rejected','dismissed')) as rejected"
                )
                ->groupBy('feature')
                ->get();
        } catch (\Throwable $e) {
            return collect();
        }
    }
}
