<?php

namespace App\Http\Controllers\Messenger;

use App\Http\Controllers\Controller;
use App\Http\Requests\Messenger\AttachmentStoreRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AttachmentController extends Controller
{
    public function store(AttachmentStoreRequest $request): JsonResponse
    {
        try {
            $data = $request->validated();
            $file = $request->file('file');
            
            // Store the file
            $filePath = storeMedia($file, "attachments/{$data['type']}s");
            
            // Generate signed URL for temporary access
            $url = getMedia($filePath, $data['type']);
            
            return response()->json([
                'status' => 200,
                'message' => 'File uploaded successfully',
                'data' => [
                    'file_path' => $filePath,
                    'file_name' => $file->getClientOriginalName(),
                    'file_size' => $file->getSize(),
                    'mime_type' => $file->getMimeType(),
                    'type' => $data['type'],
                    'url' => $url,
                ],
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Failed to upload file',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    public function signedUrl(Request $request): JsonResponse
    {
        $request->validate([
            'file_name' => 'required|string|max:255',
            'file_size' => 'required|integer|max:52428800', // 50MB
            'mime_type' => 'required|string',
        ]);

        try {
            // Generate a pre-signed URL for direct upload (if using S3)
            // For now, return a simple response indicating where to upload
            
            return response()->json([
                'status' => 200,
                'message' => 'Signed URL generated',
                'data' => [
                    'upload_url' => route('messenger.attachments.store'),
                    'method' => 'POST',
                    'headers' => [
                        'Authorization' => 'Bearer ' . $request->user()->currentAccessToken()->plainTextToken,
                    ],
                ],
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Failed to generate signed URL',
                'error' => $e->getMessage(),
            ], 500);
        }
    }
}
