<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Article;
use App\Models\MstPropertyType;
use App\Models\RelationEventDay;
use App\Models\RelationLawrestriction;
use App\Models\RelationOtherrestriction;
use App\Models\RelationShared;
use App\Services\MansionSiteSyncService;
use Illuminate\Support\Facades\Auth;

class MansionSiteSyncController extends Controller
{
    public function retry($id, MansionSiteSyncService $siteSyncService)
    {
        $companyId = (int) Auth::user()->company_id;
        $buildingId = (int) $id;
        $article = Article::where('company_id', $companyId)
            ->where('building_id', $buildingId)
            ->whereNull('mansion_id')
            ->whereIn('property', [MstPropertyType::MANSION_ID, MstPropertyType::MANSION_ID2])
            ->firstOrFail();
        $payload = $article->toArray();
        $payload['shared'] = RelationShared::where('company_id', $companyId)
            ->where('article_id', $buildingId)
            ->pluck('item_id')
            ->all();
        $payload['law_restriction'] = RelationLawrestriction::where('company_id', $companyId)
            ->where('article_id', $buildingId)
            ->pluck('item_id')
            ->all();
        $payload['other_restriction'] = RelationOtherrestriction::where('company_id', $companyId)
            ->where('article_id', $buildingId)
            ->pluck('item_id')
            ->all();
        $payload['event_day'] = RelationEventDay::where('company_id', $companyId)
            ->where('article_id', $buildingId)
            ->pluck('event_day')
            ->all();

        $result = $siteSyncService->sendOrQueueIfIdle($companyId, $buildingId, $payload);
        $redirect = redirect()->route('showEditMansion', ['id' => $buildingId]);

        if ($result->isSuccessful()) {
            return $redirect->with('site_sync_success', 'サイトへの再同期が完了しました。');
        }

        return $redirect->with(
            'site_sync_warning',
            '物件情報の保存は完了しましたが、サイトへの反映に失敗しました。自動的に再送します。'
        );
    }
}
