-- Eggtracker v2 migration — adds multi-user support to an existing database.
-- Run this ONCE on an existing install BEFORE restarting with the new image:
--
--   docker compose exec db mysql -u root -p"${MYSQL_ROOT_PASSWORD}" eggtracker < mysql/migrate_v2.sql
--
-- After running this script, restart the stack (docker compose up -d --build).
-- The API will automatically create the admin user (from ADMIN_USERNAME /
-- ADMIN_PASSWORD in .env) and assign all existing records to that admin account.
--
-- NOTE: Run this script only ONCE. Running it again will fail on the ADD COLUMN
-- statements since the columns will already exist.

USE eggtracker;

-- ── Create users table ────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS users (
    id              INT UNSIGNED    NOT NULL AUTO_INCREMENT,
    username        VARCHAR(64)     NOT NULL,
    hashed_password VARCHAR(255)    NOT NULL,
    is_admin        TINYINT(1)      NOT NULL DEFAULT 0,
    is_disabled     TINYINT(1)      NOT NULL DEFAULT 0,
    created_at      DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY uq_username (username)
) ENGINE=InnoDB;

-- ── Add user_id columns (nullable so existing rows remain valid) ───────────────
ALTER TABLE egg_collections
    ADD COLUMN user_id INT UNSIGNED NULL AFTER id,
    ADD INDEX idx_user_id (user_id);

ALTER TABLE flock_history
    ADD COLUMN user_id INT UNSIGNED NULL AFTER id,
    ADD INDEX idx_user_id (user_id);

ALTER TABLE feed_purchases
    ADD COLUMN user_id INT UNSIGNED NULL AFTER id,
    ADD INDEX idx_user_id (user_id);

ALTER TABLE other_purchases
    ADD COLUMN user_id INT UNSIGNED NULL AFTER id,
    ADD INDEX idx_user_id (user_id);

-- ── Remove old single-column unique index on egg_collections.date ─────────────
-- It will be replaced by (user_id, date) once the admin is seeded.
ALTER TABLE egg_collections DROP INDEX uq_date;

-- The API startup will:
-- 1. Create the admin user from ADMIN_USERNAME / ADMIN_PASSWORD in .env
-- 2. Set user_id = admin.id on all rows where user_id IS NULL
