<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

namespace local_kid\external;

use core_external\external_api;
use core_external\external_function_parameters;
use core_external\external_single_structure;
use core_external\external_value;
use local_kid\local\access_helper;
use local_kid\local\dashboard_favori_repository;

defined('MOODLE_INTERNAL') || die();

/**
 * Renames one of the calling user's own dashboard favoris. The ownership
 * check happens inside {@see dashboard_favori_repository::rename()} — a
 * request naming another user's favori id fails harmlessly (returns
 * success=false), never touches a row it doesn't own.
 */
class dashboard_favori_rename extends external_api {

    public static function execute_parameters(): external_function_parameters {
        return new external_function_parameters([
            'id' => new external_value(PARAM_INT, 'local_kid_dashboard_favori.id'),
            'name' => new external_value(PARAM_TEXT, 'New name'),
        ]);
    }

    public static function execute(int $id, string $name): array {
        global $USER;

        ['id' => $id, 'name' => $name] = self::validate_parameters(self::execute_parameters(), [
            'id' => $id, 'name' => $name,
        ]);

        $context = \context_system::instance();
        self::validate_context($context);
        access_helper::require_capability_or_teacher('local/kid:managedashboardfavourites', $context);

        $name = trim($name);
        if ($name === '') {
            throw new \moodle_exception('invalidparameter', 'error');
        }

        $success = dashboard_favori_repository::rename($id, (int) $USER->id, $name);

        return ['success' => $success];
    }

    public static function execute_returns(): external_single_structure {
        return new external_single_structure([
            'success' => new external_value(PARAM_BOOL, 'False if the favori does not exist or is not owned by the caller'),
        ]);
    }
}
