<?php

namespace App\Http\Controllers\Assets\Settings;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\ApiCredential;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class OktaSsoController extends Controller
{
    /**
     * Displays the Okta SSO configuration page. Creates a new credential record if one doesn't exist.
     *
     * @return \Illuminate\View\View The view for the Okta SSO settings index
     */
    public function index()
    {
        $credential = ApiCredential::firstOrCreate([
            'slug' => 'okta_sso'
        ], [
            'api_name' => 'Okta SSO',
            'integration_status' => 0
        ]);

        return view('settings.okta-sso.index', compact('credential'));
    }
    
    /**
     * Update the Okta SSO configuration.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\ApiCredential  $oktaSso
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, ApiCredential $oktaSso)
    {
        try {

            // Common validation rules
            $rules = [
                'sign_out_url'  => 'required_if:integration_status,==,1',
                'sign_on_url'   => 'required_if:integration_status,==,1',
                'issuer_url'    => 'required_if:integration_status,==,1',
            ];

            // Additional rule only when creating new or when data is empty
            if (empty($oktaSso->data)) {
                $rules['signing_certificate'] = 'required_if:integration_status,==,1';
            }

            $request->validate($rules);

            $updateData = [
                'url'                   => $request->issuer_url,
                'user_name'             => $request->sign_on_url,
                'project'               => $request->sign_out_url,
                'integration_status'    => (int)$request->integration_status
            ];

            // Only update certificate if provided
            if (request()->has('signing_certificate') && !empty(request()->signing_certificate)) {
                $updateData['data'] = $request->signing_certificate;
            }

            $oktaSso->update($updateData);

            Cache::forget('okta_sso_config');

            return redirect()->route('okta-sso.index')->with('message', __('message.updated'));
        } catch (Exception $e) {
            Log::error('Okta SSO update failed: ' . $e->getMessage());
            return redirect(route('okta-sso.index'))->with('error', 'Something went wrong. Try again later');
        }
    }
}
