<?php

namespace App\Models;

use App\Models\Concerns\BelongsToCompany;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

/**
 * A single hostname a company answers to — either a subdomain we hand out
 * (acme.abic-elearning.com) or a domain the company already owns and has
 * pointed at us (bba.com). ResolveTenant middleware looks the current
 * request's Host header up here to work out which Company is being served.
 *
 * BelongsToCompany is safe here, unlike on User: the one cross-tenant
 * lookup that must see every company's domains — ResolveTenant's own
 * Host -> Domain lookup — runs before any company is bound for the
 * request, so the scope is a no-op exactly when it needs to be. Once a
 * company IS bound, every later Domain query (the admin's own "my
 * domains" screen, route-model binding included) is automatically
 * restricted to that company — a company admin can't view or verify
 * another company's domain by guessing its ID.
 */
class Domain extends Model
{
    use HasFactory, BelongsToCompany;

    protected $guarded = ['id'];

    protected $casts = [
        'verified_at' => 'datetime',
        'is_primary' => 'boolean',
    ];

    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }

    public function isCustom(): bool
    {
        return $this->type === 'custom';
    }

    public function isVerified(): bool
    {
        return $this->isCustom() ? $this->verified_at !== null : true;
    }

    /**
     * A short-lived token the company proves ownership of a custom domain
     * with, by publishing it as a TXT record before we'll issue a
     * certificate or route traffic for it. See Phase 3.
     */
    public static function generateVerificationToken(): string
    {
        return 'abic-verify-' . Str::random(32);
    }
}
