<?php

namespace App\Http\Controllers\Api\V1\Audit;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\Audit\TriggerAuditLogIndexRequest;
use App\Http\Requests\Audit\TriggerAuditRollbackRequest;
use App\Services\Audit\AuditRollbackService;
use App\Services\Audit\TriggerAuditLogService;

class TriggerAuditLogController extends Controller
{
    public function __construct(
        protected TriggerAuditLogService $service,
        protected AuditRollbackService $rollbackService,
    ) {}

    /**
     * 트리거 감사 로그 목록 조회
     */
    public function index(TriggerAuditLogIndexRequest $request)
    {
        return ApiResponse::handle(function () use ($request) {
            return $this->service->paginate($request->validated());
        }, __('message.fetched'));
    }

    /**
     * 트리거 감사 로그 상세 조회
     */
    public function show(int $id)
    {
        return ApiResponse::handle(function () use ($id) {
            return \App\Models\Audit\TriggerAuditLog::findOrFail($id);
        }, __('message.fetched'));
    }

    /**
     * 특정 레코드의 변경 이력
     */
    public function recordHistory(string $tableName, string $rowId)
    {
        return ApiResponse::handle(function () use ($tableName, $rowId) {
            return $this->service->recordHistory($tableName, $rowId);
        }, __('message.fetched'));
    }

    /**
     * 통계 조회
     */
    public function stats()
    {
        return ApiResponse::handle(function () {
            $tenantId = request()->query('tenant_id');

            return $this->service->stats($tenantId ? (int) $tenantId : null);
        }, __('message.fetched'));
    }

    /**
     * 롤백 SQL 미리보기
     */
    public function rollbackPreview(int $id)
    {
        return ApiResponse::handle(function () use ($id) {
            return [
                'audit_id' => $id,
                'rollback_sql' => $this->rollbackService->generateRollbackSQL($id),
            ];
        }, __('message.fetched'));
    }

    /**
     * 롤백 실행
     */
    public function rollbackExecute(TriggerAuditRollbackRequest $request, int $id)
    {
        return ApiResponse::handle(function () use ($id) {
            return $this->rollbackService->executeRollback($id);
        }, __('message.updated'));
    }
}
