-- WhereWoof canonical schema (Phase 1)
-- Source of truth until Laravel takes over migration ownership (Phase 4).
-- Applied by: make db-up (frontend/cmd/migrate)

CREATE TABLE IF NOT EXISTS users (
    id            BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email         TEXT NOT NULL UNIQUE,
    password_hash TEXT NOT NULL,
    name          TEXT,
    phone         TEXT,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS tags (
    id          BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    tag_code    TEXT NOT NULL UNIQUE,      -- printed on QR + NFC, public identifier
    owner_id    BIGINT REFERENCES users(id),
    status      TEXT NOT NULL DEFAULT 'unset'
                CHECK (status IN ('unset', 'active', 'suspended')),
    item_type   TEXT CHECK (item_type IN ('dog', 'cat', 'baggage', 'skis', 'other')),
    description TEXT,
    photo_url   TEXT,
    phone       TEXT,                       -- owner contact phone (shown via tel:)
    address     TEXT,
    notes       TEXT,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS scans (
    id              BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    tag_id          BIGINT NOT NULL REFERENCES tags(id),
    scanned_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    lat             DOUBLE PRECISION,
    lng             DOUBLE PRECISION,
    location_shared BOOLEAN NOT NULL DEFAULT FALSE,
    scanner_phone   TEXT,
    alert_sent      BOOLEAN NOT NULL DEFAULT FALSE
);

-- Phase 2: per-tag SMS alert control. Idempotent so existing DBs migrate cleanly.
ALTER TABLE tags ADD COLUMN IF NOT EXISTS sms_enabled BOOLEAN NOT NULL DEFAULT TRUE;
