<?php

namespace App\Services\Construction;

use App\Models\Construction\StructureReview;
use App\Services\Service;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;

class StructureReviewService extends Service
{
    /**
     * 구조검토 목록 조회
     */
    public function index(array $params): LengthAwarePaginator
    {
        $tenantId = $this->tenantId();

        $query = StructureReview::query()
            ->where('tenant_id', $tenantId);

        // 검색 필터
        if (! empty($params['search'])) {
            $search = $params['search'];
            $query->where(function ($q) use ($search) {
                $q->where('review_number', 'like', "%{$search}%")
                    ->orWhere('partner_name', 'like', "%{$search}%")
                    ->orWhere('site_name', 'like', "%{$search}%")
                    ->orWhere('review_company', 'like', "%{$search}%")
                    ->orWhere('reviewer_name', 'like', "%{$search}%");
            });
        }

        // 상태 필터
        if (! empty($params['status'])) {
            $query->where('status', $params['status']);
        }

        // 거래처 필터
        if (! empty($params['partner_id'])) {
            $query->where('partner_id', $params['partner_id']);
        }

        // 현장 필터
        if (! empty($params['site_id'])) {
            $query->where('site_id', $params['site_id']);
        }

        // 날짜 범위 필터 (의뢰일 기준)
        if (! empty($params['start_date'])) {
            $query->where('request_date', '>=', $params['start_date']);
        }
        if (! empty($params['end_date'])) {
            $query->where('request_date', '<=', $params['end_date']);
        }

        // 활성화 상태 필터
        if (isset($params['is_active'])) {
            $query->where('is_active', $params['is_active']);
        }

        // 정렬
        $sortBy = $params['sort_by'] ?? 'created_at';
        $sortDir = $params['sort_dir'] ?? 'desc';
        $query->orderBy($sortBy, $sortDir);

        // 페이지네이션
        $perPage = $params['per_page'] ?? 20;

        return $query->paginate($perPage);
    }

    /**
     * 구조검토 상세 조회
     */
    public function show(int $id): StructureReview
    {
        $tenantId = $this->tenantId();

        return StructureReview::query()
            ->where('tenant_id', $tenantId)
            ->with(['site', 'creator', 'updater'])
            ->findOrFail($id);
    }

    /**
     * 구조검토 등록
     */
    public function store(array $data): StructureReview
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        return DB::transaction(function () use ($data, $tenantId, $userId) {
            $review = StructureReview::create([
                'tenant_id' => $tenantId,
                'review_number' => $data['review_number'] ?? null,
                'partner_id' => $data['partner_id'] ?? null,
                'partner_name' => $data['partner_name'] ?? null,
                'site_id' => $data['site_id'] ?? null,
                'site_name' => $data['site_name'] ?? null,
                'request_date' => $data['request_date'] ?? null,
                'review_company' => $data['review_company'] ?? null,
                'reviewer_name' => $data['reviewer_name'] ?? null,
                'review_date' => $data['review_date'] ?? null,
                'completion_date' => $data['completion_date'] ?? null,
                'status' => $data['status'] ?? StructureReview::STATUS_PENDING,
                'file_url' => $data['file_url'] ?? null,
                'remarks' => $data['remarks'] ?? null,
                'is_active' => $data['is_active'] ?? true,
                'created_by' => $userId,
                'updated_by' => $userId,
            ]);

            return $review;
        });
    }

    /**
     * 구조검토 수정
     */
    public function update(int $id, array $data): StructureReview
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        return DB::transaction(function () use ($id, $data, $tenantId, $userId) {
            $review = StructureReview::query()
                ->where('tenant_id', $tenantId)
                ->findOrFail($id);

            $review->fill([
                'review_number' => $data['review_number'] ?? $review->review_number,
                'partner_id' => $data['partner_id'] ?? $review->partner_id,
                'partner_name' => $data['partner_name'] ?? $review->partner_name,
                'site_id' => $data['site_id'] ?? $review->site_id,
                'site_name' => $data['site_name'] ?? $review->site_name,
                'request_date' => $data['request_date'] ?? $review->request_date,
                'review_company' => $data['review_company'] ?? $review->review_company,
                'reviewer_name' => $data['reviewer_name'] ?? $review->reviewer_name,
                'review_date' => $data['review_date'] ?? $review->review_date,
                'completion_date' => $data['completion_date'] ?? $review->completion_date,
                'status' => $data['status'] ?? $review->status,
                'file_url' => $data['file_url'] ?? $review->file_url,
                'remarks' => $data['remarks'] ?? $review->remarks,
                'is_active' => $data['is_active'] ?? $review->is_active,
                'updated_by' => $userId,
            ]);

            $review->save();

            return $review->fresh();
        });
    }

    /**
     * 구조검토 삭제
     */
    public function destroy(int $id): bool
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        return DB::transaction(function () use ($id, $tenantId, $userId) {
            $review = StructureReview::query()
                ->where('tenant_id', $tenantId)
                ->findOrFail($id);

            $review->deleted_by = $userId;
            $review->save();
            $review->delete();

            return true;
        });
    }

    /**
     * 구조검토 일괄 삭제
     */
    public function bulkDestroy(array $ids): bool
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        return DB::transaction(function () use ($ids, $tenantId, $userId) {
            $reviews = StructureReview::query()
                ->where('tenant_id', $tenantId)
                ->whereIn('id', $ids)
                ->get();

            foreach ($reviews as $review) {
                $review->deleted_by = $userId;
                $review->save();
                $review->delete();
            }

            return true;
        });
    }

    /**
     * 구조검토 통계 조회
     */
    public function stats(array $params): array
    {
        $tenantId = $this->tenantId();

        $query = StructureReview::query()
            ->where('tenant_id', $tenantId);

        // 날짜 범위 필터
        if (! empty($params['start_date'])) {
            $query->where('request_date', '>=', $params['start_date']);
        }
        if (! empty($params['end_date'])) {
            $query->where('request_date', '<=', $params['end_date']);
        }

        $totalCount = (clone $query)->count();
        $pendingCount = (clone $query)->where('status', StructureReview::STATUS_PENDING)->count();
        $completedCount = (clone $query)->where('status', StructureReview::STATUS_COMPLETED)->count();

        return [
            'total' => $totalCount,
            'pending' => $pendingCount,
            'completed' => $completedCount,
        ];
    }
}
