<?php

namespace BitApps\PiPro\src\Integrations\Airtable;

// Prevent direct script access
if (!\defined('ABSPATH')) {
    exit;
}

final class AirtableService
{
    private $http;

    private $baseUrl;

    /**
     * AirtableService constructor.
     *
     * @param mixed $httpClient
     * @param mixed $baseUrl
     */
    public function __construct($httpClient, $baseUrl)
    {
        $this->http = $httpClient;
        $this->baseUrl = $baseUrl;
    }

    /**
     * Create a record in Airtable.
     *
     * @param string $baseId
     * @param string $tableIdOrName
     * @param array  $fields
     *
     * @return array
     */
    public function createRecord($baseId, $tableIdOrName, $fields)
    {
        $records = ['records' => $fields];

        $response = $this->http->request(
            $this->baseUrl . $baseId . '/' . $tableIdOrName,
            'POST',
            wp_json_encode($records),
        );
        if (isset($response->records) && \is_array($response->records) && \count($response->records) > 0) {
            $message = 'Record created successfully';
        } else {
            $message = $this->getErrorMessage($response, 'Failed to create record');
        }

        return [
            'status_code' => $this->http->getResponseCode(),
            'payload'     => [],
            'response'    => $response,
            'message'     => $message,
        ];
    }

    /**
     * Update a record in Airtable.
     *
     * @param string $baseId
     * @param string $tableIdOrName
     * @param string $recordId
     * @param array  $fields
     *
     * @return array
     */
    public function updateRecord($baseId, $tableIdOrName, $recordId, $fields)
    {
        $response = $this->http->request(
            $this->baseUrl . $baseId . '/' . $tableIdOrName . '/' . $recordId,
            'PATCH',
            wp_json_encode(['fields' => $fields])
        );
        if (isset($response->id, $response->fields)) {
            $message = 'Record updated successfully';
        } else {
            $message = $this->getErrorMessage($response, 'Failed to update record');
        }

        return [
            'status_code' => $this->http->getResponseCode(),
            'payload'     => [],
            'response'    => $response,
            'message'     => $message,
        ];
    }

    /**
     * Delete a record from Airtable.
     *
     * @param string $baseId
     * @param string $tableIdOrName
     * @param string $recordId
     *
     * @return array
     */
    public function deleteRecord($baseId, $tableIdOrName, $recordId)
    {
        $response = $this->http->request(
            $this->baseUrl . $baseId . '/' . $tableIdOrName . '/' . $recordId,
            'DELETE',
            []
        );

        if (isset($response->deleted) && $response->deleted === true && isset($response->id)) {
            $message = 'Record deleted successfully';
        } else {
            $message = $this->getErrorMessage($response, 'Failed to delete record');
        }

        return [
            'status_code' => $this->http->getResponseCode(),
            'payload'     => [],
            'response'    => $response,
            'message'     => $message,
        ];
    }

    /**
     * Get a record from Airtable.
     *
     * @param string $baseId
     * @param string $tableIdOrName
     * @param string $recordId
     *
     * @return array
     */
    public function searchRecord($baseId, $tableIdOrName, $recordId)
    {
        $response = $this->http->request(
            $this->baseUrl . $baseId . '/' . $tableIdOrName . '/' . $recordId,
            'GET',
            []
        );

        if (isset($response->id, $response->fields)) {
            $message = 'Record fetched successfully';
        } else {
            $message = $this->getErrorMessage($response, 'Record not found');
        }

        return [
            'status_code' => $this->http->getResponseCode(),
            'payload'     => [],
            'response'    => $response,
            'message'     => $message,
        ];
    }

    /**
     * Get records from Airtable table.
     *
     * @param string $baseId
     * @param string $tableIdOrName
     *
     * @return array
     */
    public function getRecords($baseId, $tableIdOrName)
    {
        $response = $this->http->request(
            $this->baseUrl . $baseId . '/' . $tableIdOrName,
            'GET',
            []
        );
        if (isset($response->records) && \is_array($response->records)) {
            $message = 'Records fetched successfully';
        } else {
            $message = $this->getErrorMessage($response, 'Failed to fetch records');
        }

        return [
            'status_code' => $this->http->getResponseCode(),
            'payload'     => [],
            'response'    => $response,
            'message'     => $message,
        ];
    }

    /**
     * Extract error message from API response.
     *
     * @param object $response
     * @param string $defaultMessage
     *
     * @return string
     */
    private function getErrorMessage($response, $defaultMessage)
    {
        if (isset($response->error)) {
            return \is_string($response->error) ? $response->error : ($response->error->message ?? $defaultMessage);
        }

        return $defaultMessage;
    }
}
