<?php

namespace App\Http\Controllers\Api;

use App\Models\SupportTicket;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SupportController extends BaseApiController
{
    public function index()
    {
        $user = Auth::user();
        $tickets = SupportTicket::where('user_id', $user->id)
            ->orderByDesc('created_at')
            ->get();

        return $this->successResponse($tickets);
    }

    public function store(Request $request)
    {
        $request->validate([
            'subject' => 'required|string|max:255',
            'message' => 'required|string',
            'priority' => 'sometimes|in:low,normal,high,urgent',
        ]);

        $user = Auth::user();
        $association = $user->associations()->first();

        $ticket = SupportTicket::create([
            'association_id' => $association->id,
            'user_id' => $user->id,
            'subject' => $request->subject,
            'message' => $request->message,
            'priority' => $request->priority ?? 'normal',
            'status' => 'open',
        ]);

        return $this->successResponse($ticket, 'Support ticket created successfully', 201);
    }

    public function show($id)
    {
        $user = Auth::user();
        $ticket = SupportTicket::where('user_id', $user->id)
            ->findOrFail($id);

        return $this->successResponse($ticket);
    }
}
