<?php

   namespace App\Http\Controllers\Api\V1;

   use App\Http\Controllers\Controller;
   use App\Http\Resources\Api\V1\LinkCbtOfflineResource;
   use App\Http\Resources\Api\V1\LinkProfileResource;
   use App\Models\Link;
   use App\Models\LinkProfile;
   use Illuminate\Http\Request;
   use Illuminate\Support\Facades\Cache;

   class LinkController extends Controller
   {
      public function show($npsn = NULL) {
         if(!$npsn){
            return response()->json([
               'status'  => 'error',
               'message' => 'Parameter NPSN wajib diisi.',
            ], 400);
         }
         $profile = LinkProfile::with([
            'links' => function($q) {
               $q
                  ->where('is_active', true)
                  ->where('is_cbt_offline', false)
                  ->orderBy('order');
            },
            'lembaga',
         ])->where('link_profile_npsn', $npsn)->first();
         if(!$profile){
            return response()->json([
               'status'  => 'error',
               'message' => 'Link profile dengan NPSN tersebut tidak ditemukan.',
            ], 404);
         }

         return response()->json([
            'status' => 'success',
            'data'   => new LinkProfileResource($profile),
         ]);
      }

      public function showByCbt($npsn = NULL) {
         if(!$npsn){
            return response()->json(['status' => 'error', 'message' => 'NPSN wajib diisi.'], 400);
         }
         $cacheKey = "cbt_offline_profile_{$npsn}";
         $data     = Cache::get($cacheKey);
         if(!$data){
            // Jika pakai driver FILE, pastikan DB_CONNECTION di .env benar karena
            // Laravel akan otomatis menggunakan table 'cache_locks' jika lock dipanggil.
            // Jika kamu tidak mau pakai table lock, gunakan logic "remember" yang lebih simple:
            $data = Cache::remember($cacheKey, now()->addMinutes(30), function() use ($npsn) {
               $profile = LinkProfile::with([
                  'links' => function($q) {
                     $q
                        ->select('id', 'link_profile_id', 'title', 'url', 'order')
                        ->where('is_active', true)
                        ->where('is_cbt_offline', true)
                        ->orderBy('order');
                  },
                  'lembaga:id,npsn,name,level,logo',
               ])
                                     ->where('link_profile_npsn', $npsn)
                                     ->first();

               return $profile ? (new LinkCbtOfflineResource($profile))->resolve() : NULL;
            });
         }
         if(!$data){
            return response()->json(['status' => 'error', 'message' => 'Data tidak ditemukan.'], 404);
         }

         return response()->json(['status' => 'success', 'data' => $data]);
      }
   }
